[英]Adding Error Bars to ggplot2 Boxplot in R?
alphastats<-summarySE(map, measurevar="shannon", groupvars=c("age_class"))
age_class N shannon sd se ci
1 Non_Smoker 66 5.473424 0.4152997 0.05111986 0.1020934
2 Old_Smoker 47 5.271223 0.6046414 0.08819601 0.1775294
3 Young_Smoker 17 5.324977 0.8682071 0.21057116 0.4463909
嗨,我想在R中的ggplot2箱线图中添加误差线。我为上述数据帧创建了三个组中每个组的必要标准误差数据。
ggplot() +
geom_boxplot(data=map, aes(x=age_class, y=shannon, fill=age_class), na.rm= TRUE ) +
theme_bw() +
geom_jitter(data=map, aes(x=age_class, y=shannon), position=position_jitter(width=0.1)) +
labs(x="Group", y="Shannon Value") +
guides(fill=guide_legend(title="Group Type")) +
annotate("text", x=0.75, y=3.5, size=3, label=paste0("p-value =",alpha_p_round)) +
geom_errorbar(data=alphastats, aes(ymin=shannon-se, ymax=shannon+se))
当我尝试通过gg_errorbar()添加错误栏时,出现错误:
“ eval(expr,envir,enclos)中的错误:找不到对象'x'
另外:警告消息:
1:在min(x,na.rm = na.rm)中:
没有min的必填项; 返回Inf
2:在max(x,na.rm = na.rm)中:
没有max的必填项; 返回-Inf
3:在min(diff(sort(x)))中:没有min的必填参数; 返回
信息
有人可以帮我弄清楚我在做什么错吗?
您的示例不可复制,但是根据您提供的示例数据,以下工作有效:
alphastats <- read.table(
text = " age_class N shannon sd se ci
1 Non_Smoker 66 5.473424 0.4152997 0.05111986 0.1020934
2 Old_Smoker 47 5.271223 0.6046414 0.08819601 0.1775294
3 Young_Smoker 17 5.324977 0.8682071 0.21057116 0.4463909", header = T)
library(ggplot2);
ggplot(alphastats, aes(x = age_class, y = shannon)) +
geom_point() +
theme_bw() +
labs(x = "Group", y = "Shannon Value") +
guides(fill=guide_legend(title = "Group Type")) +
geom_errorbar(aes(ymin = shannon - se, ymax = shannon + se))
您尚未在geom_errorbar
提供x=age_class
,因此geom_errorbar
不知道误差线的x坐标。 如果将x=age_class
添加到geom_errorbar
,则代码将起作用。
您也可以稍微缩短代码。 由于geom_errorbar
使用与其他两个geoms相同的x
和y
变量,因此另一个选择是执行ggplot(map, aes(x=age_class, y=shannon)) + ...
这意味着所有geoms将使用map
数据帧和age_class
和shannon
列x和y,分别除非额外的事情。
然后,在geom_errorbar
,您只需为其提供新的数据框以及ymin
和ymax
美观度即可。 但是,除非您希望geom_errorbar
为主ggplot
调用中使用的列使用不同的列,否则无需提供x
或y
美观。
因此,代码将是:
ggplot(map, aes(x=age_class, y=shannon)) +
geom_boxplot(aes(fill=age_class)) +
geom_jitter(width=0.1) + # geom_jitter takes a direct width argument. You can use the `position` argument, but it's not necessary.
geom_errorbar(data=alphastats, aes(ymin=shannon-se, ymax=shannon+se)) +
labs(x="Group", y="Shannon Value", fill="Group Type") + # Note that the fill label has been moved to labs
annotate("text", x=0.75, y=3.5, size=3, label=paste0("p-value =", alpha_p_round)) +
theme_bw()
您确定要geom_jitter
吗? 如果您希望shannon
的平均值与误差线一致,请使用geom_point
。 如果您希望它们偏移相同的量,请使用position_nudge
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.