【发布时间】:2020-09-23 20:49:58
【问题描述】:
我正在尝试在 ggplot 中使用 geom_text() 将样本大小放置在条形图上,并由 ggplot 确定定义的限制。对于我的大部分地块,我已经能够将文本放置的 y 值指定为 0。但是,对于一些地块,CI 条延伸到 0 以下。
为了防止在 CI 条上打印样本大小,我想生成代码,指定 geom_text() 的 y 值与定义 x 轴的绘图边距相关。这个想法将生成相对于 x 轴的通用代码,因此无论 y 的最小值在图中的哪个位置,该代码都可以应用于我的所有图。理想情况下,如果可能的话,我想调整我的绘图代码来实现这一点。提前感谢您的意见!
绘图数据库
data <- structure(list(Site_long = structure(c(2L, 2L, 1L, 1L), .Label = c("Hanauma Bay",
"Waikiki"), class = "factor"), Shelter = structure(c(1L, 2L,
1L, 2L), .Label = c("Low", "High"), class = c("ordered", "factor"
)), mean = c(0.096818329015544, 0.140368187765273, 0.364490168863912,
0.452663275851282), sd = c(0.358269615215823, 0.442381836749624,
0.431417057945072, 0.461599742148954), lower = c(-0.13725115292546,
-0.148654612244481, 0.198658790631641, 0.337761753133984), upper = c(0.330887810956549,
0.429390987775027, 0.530321547096184, 0.56756479856858), sample_size = c(9L,
9L, 26L, 62L)), row.names = c(NA, -4L), groups = structure(list(
Site_long = structure(1:2, .Label = c("Hanauma Bay", "Waikiki"
), class = "factor"), .rows = structure(list(3:4, 1:2), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
绘图代码
mult_compare_growth_all <- c("AB", "B", "A", "AB")
growth_plot <- ggplot(data = data, aes(fill=Shelter, y=mean, x=Site_long)) +
geom_bar(position = "dodge", stat="identity", width = .8) +
scale_x_discrete(limits = position) +
geom_errorbar(aes(ymin = lower, ymax = upper), position = position_dodge(.8), width = .1) +
geom_text(aes(label = mult_compare_growth_all, y = data$upper), vjust = -.5, position = position_dodge(width = 0.8), size = 4) +
scale_fill_grey(name = "Shelter", start = .8, end = .2) +
labs(x = "Site", y = expression(paste("Coral growth (cm"^"2","/quarter)"))) +
theme_classic(base_size = 14.5) +
theme(text = element_text(size = 18), legend.position = "none",
axis.title.x = element_blank(),
axis.text.y = element_text(angle = 90),
axis.text.x = element_blank())
【问题讨论】:
-
您希望将样本大小放在哪里?在黑色竖线下方?
-
是的,我想让值刚好在 x 轴上方,而 x 轴应该总是低于 CI 条
-
不错!我想我有一个简单的解决方案..我已经发布了答案,请查看。