❝本节来介绍如何使用「cowplot」包所提供的「ggdraw」函数来对图形做额外的注释
加载R包
代码语言:javascript复制library(tidyverse)
library(cowplot)
导入数据
代码语言:javascript复制test <- read_tsv("data.xls")
数据清洗
代码语言:javascript复制summ_df <- test %>%
group_by(sd, n, wdh) %>%
summarise(n = n(),
avg_val = mean(val),
conf_int_lower = avg_val - 1.96 * sd(val)/sqrt(n),
conf_int_upper = avg_val 1.96 * sd(val)/sqrt(n))
绘制主图
代码语言:javascript复制plot <- ggplot(test)
geom_jitter(aes(x = val, y = wdh), height = 0.02, col = "steelblue4", alpha = 0.4)
geom_point(data = summ_df, aes(x = avg_val, y = wdh-0.3), col = "steelblue4")
geom_errorbarh(data = summ_df,
aes(xmin = conf_int_lower, xmax = conf_int_upper, y = wdh-0.3),
height = 0.3)
geom_vline(xintercept = 0, col = "steelblue4", size = 0.5)
facet_grid(sd ~ n)
expand_limits(y = c(0.5,4.5))
labs(y = "Standard deviation",
x = "Sample size")
theme(axis.text = element_blank(),
axis.title.x.bottom = element_blank(),
axis.title.y.left = element_blank(),
axis.ticks = element_blank(),
panel.background = element_rect(fill="white",colour = "#75C500"),
strip.text = element_text(size = 16),
strip.background = element_rect(fill = "#75C500"),
panel.border = element_rect(linetype = "solid",fill=NA,colour = "#75C500"),
panel.spacing = unit(0.05,"in"))
图形注释
代码语言:javascript复制❝以前我们主要使用「annotation_custom」函数来进行注释,在此我们使用
ggdraw
函数后可以通过draw_*
函数来添加新的图形;也算是一种新的方法 ❞
ggdraw(xlim = c(0, 1.2), ylim = c(-0.2,0.95))
draw_plot(plot,x = 0, y = -0.2)
draw_grob(grid::grid.rect(gp=grid::gpar(fill="grey90",col="grey90")),
x=0.02,y=0.8,height = 0.1,width=0.95)
draw_grob(grid::grid.rect(gp=grid::gpar(fill="#75C500",col="#75C500")),
x=0.955,y=0.7,height = 0.08549,width=0.036)
draw_line(x = c(0.1,0.8), y = c(0.86,0.86), arrow = arrow(), lineend = "butt",
size = 2, col = "steelblue4")
draw_line(x = c(1.1,1.1), y = c(0.6,-0.1), arrow = arrow(), lineend = "butt",
size = 2, col = "sandybrown")
draw_text(text = "Sample size", size = 16, x = 0.45, y = 0.83)
draw_text(text = "Standard deviation", size = 16, x = 1.05, y = 0.25,
angle = -90)
ggsave(filename ="F.pdf",width=10.57,height=6.29,unit="in",dpi=300)
❝可以看到整个过程还是很简单的,喜欢的观众老爷欢迎分享转发