本节介绍如何给图像添加花括号用于数据注释,喜欢的小伙伴欢迎关注收藏,更多精彩内容敬请期待
加载R包
library(tidyverse)
library(pBrackets)
library(glue)
library(ggtext)
定义函数
bracketsGrob <- function(...){
l <- list(...)
e <- new.env()
e$l <- l
grid:::recordGrob( {
do.call(grid.brackets, l)
}, e)
}
数据可视化
p <- iris %>% group_by(Species) %>%
summarise(mean_Sepal.Length=mean(Sepal.Length),
sd_Sepal.Length=sd(Sepal.Length)) %>%
ggplot(aes(Species, mean_Sepal.Length)) +
geom_col(aes(fill=Species),width=0.5) +
scale_y_continuous(limits=c(0,9),expand=c(0,0)) +
theme_minimal() +
labs(x = "Species",y = "mean_Sepal.Length",
title = "The infamous Iris plot", caption = "2021-7-4") +
theme(axis.title.x = element_markdown(color="red",vjust=0.5),
axis.line = element_line(color = "#3D4852"),
axis.ticks = element_line(color = "#3D4852"),
panel.grid.major.y = element_line(color = "#DAE1E7"),
panel.grid.major.x = element_blank(),
plot.title = element_text(size = 20, face = "bold",
margin = margin(b = 30)),
plot.margin = unit(rep(1, 4),"cm"),
axis.text = element_text(size = 13, color = "#22292F"),
axis.title = element_text(size = 12, hjust = 1),
axis.title.y = element_text(margin = margin(r = 12)),
axis.text.y = element_text(margin = margin(r = 5)),
axis.text.x = element_text(margin = margin(t = 5)),
plot.caption = element_text(
size = 12, face = "italic",
color = "#606F7B", margin = margin(t = 12)),
legend.position="top")+
scale_x_discrete(limits=c("setosa","virginica","versicolor"))+
scale_fill_brewer(palette="Blues")
定义括号位置
b1 <- bracketsGrob(x1=0.1,y1=0.1,x2=0.1,y2=0.72,h=0.025,
lwd=2,col="black")
b2 <- bracketsGrob(x1=0.2,y1=0.95,x2=0.5,y2=0.95,
h=0.05,lwd=2, col="black")
b3 <- bracketsGrob(x1=0.5,y1=0.08,x2=0.81,y2=0.08,
h=-0.05,lwd=2, col="black")
b4 <- bracketsGrob(x1=0.9,y1=0.1,x2=0.9,y2=0.95,
h=-0.05,lwd=2, col="black")
p + annotation_custom(b1)+
annotation_custom(b2)+
annotation_custom(b3)+
annotation_custom(b4)+
scale_y_continuous(expand=c(0.1,0))
喜欢的小伙伴欢迎关注我的公众号
R语言数据分析指南,持续分享数据可视化的经典案例及一些生信知识,希望对大家有所帮助
网友评论