如何在ggplot2中给我的条形图添加SE误差条?

10

我使用ggplot2制作了一个简单的条形图,比较了2种昆虫物种的雄性和雌性平均寿命(年龄)。我的代码如下,其中“数据集”就是我的数据集......

    gplot(dataset, aes(Species, Age, fill=Sex))+
stat_summary(fun.y = mean, geom = "bar", position = "dodge")+
scale_fill_manual(values = c("Grey25", "Grey"))+
theme(legend.title = element_blank())+
scale_y_continuous(limits = c(0,15))

我尝试使用以下代码手动输入平均值±标准误来设置误差线的界限。为了简单起见,假设物种1雄性的平均值为10,标准误为0.5。

geom_errorbar(aes(ymin=9.5, ymax=10.5),width=.2,position=position_dodge(.9))

这段代码确实可以运行,但它为图表中的每个柱设置了相同的误差线。

我该如何添加与图表中每个柱相应的SE相等的误差线?

我对ggplot和R都比较新,所以任何帮助/建议都受欢迎。


你需要首先计算每个柱子的误差和平均值,并将它们变异到你的数据集中。然后将 yminymax 设置为这些列。 - M--
这可能会对您有所帮助。http://environmentalcomputing.net/plotting-with-ggplot-bar-plots-with-error-bars/ - M--
我似乎无法正确使用yminymax。我按照您提供的链接尝试了鸢尾花数据的示例,但也不起作用...我无法通过group_by(Species)。出现以下错误消息:Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "factor"。 - Stéphane
2个回答

29

您只需在图表中添加stat_summary(geom = "errorbar", fun.data = mean_se, position = "dodge"),就足以满足需求:


library(ggplot2)

ggplot(diamonds, aes(cut, price, fill = color)) +
  stat_summary(geom = "bar", fun = mean, position = "dodge") +
  stat_summary(geom = "errorbar", fun.data = mean_se, position = "dodge")

如果您更喜欢事先计算出值,可以像这样进行:

library(tidyverse)
pdata <- diamonds %>% 
  group_by(cut, color) %>% 
  summarise(new = list(mean_se(price))) %>% 
  unnest(new)


pdata %>% 
  ggplot(aes(cut, y = y, fill = color)) +
  geom_col(position = "dodge") +
  geom_errorbar(aes(ymin = ymin, ymax = ymax), position = "dodge")

你建议我添加的那行代码起作用了。谢谢。 - Stéphane

4

您可以使用geom_errorbar几何对象在条形图上添加误差线。

您需要提供yminymax,因此需要手动计算。

geom_errorbar帮助页面中获取:

p + geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接