【问题标题】:How do I add SE error bars to my barplot in ggplot2?如何在 ggplot2 中将 SE 误差线添加到我的条形图中?
【发布时间】:2020-02-28 18:25:18
【问题描述】:

我用 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))

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

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

此代码确实有效,但它为我的绘图中的每个条设置了相同的误差条。

如何为绘图中的每个条添加等于相应 SE 的误差条?

总的来说,我对 ggplot 和 R 相当陌生,因此欢迎任何帮助/建议。

【问题讨论】:

  • 您需要首先计算每个柱的误差和均值,并将它们变异到您的数据集中。然后将yminymax 设置为这些列。
  • 这可能会对您有所帮助。 environmentalcomputing.net/…
  • 我似乎无法让yminymax正常工作。我按照您提供的链接尝试了使用虹膜数据的示例,但这也不起作用...我无法通过group_by(Species)。出现以下错误消息:UseMethod("group_by_") 中的错误:没有适用于“group_by_”的方法应用于“因子”类的对象。

标签: r ggplot2 bar-chart errorbar


【解决方案1】:

您只需将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")

【讨论】:

  • 您建议我添加的代码行有效。谢谢。
【解决方案2】:

您可以使用geom_errorbar geom 在条形图上添加错误栏。

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

来自geom_errorbar 帮助页面:

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

【讨论】:

    猜你喜欢
    • 2016-01-04
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多