首页 > 解决方案 > 如何在 R 中的 ggplot 中为条形图添加误差线

问题描述

我最近尝试将误差线添加到我在 R 的 ggplot 中创建的条形图中。但是,当我查找 geom_errorbar 时,似乎唯一记录在案的方法是创建另一个包含 ymin 和 ymax 的数据框每个条形图,并使用该 stat='identity' 属性绘制条形图,这看起来很麻烦。

例如,这是出现在 geom_errorbar 帮助页面中的示例:

df <- data.frame(
  trt = factor(c(1, 1, 2, 2)),
  resp = c(1, 5, 3, 4),
  group = factor(c(1, 2, 1, 2)),
  se = c(0.1, 0.3, 0.3, 0.2)
)
df2 <- df[c(1,3),]

# Define the top and bottom of the errorbars
limits <- aes(ymax = resp + se, ymin=resp - se)

p <- ggplot(df, aes(fill=group, y=resp, x=trt))
p + geom_bar(position="dodge", stat="identity")

# Because the bars and errorbars have different widths
# we need to specify how wide the objects we are dodging are
dodge <- position_dodge(width=0.9)
p + geom_bar(position=dodge) + geom_errorbar(limits, position=dodge, width=0.25)

难道没有更好的方法来做到这一点而不必使用 stat='identity' 绘图吗?

标签: rggplot2statisticsggplotly

解决方案


使用 geom_errobars 有一种更简单的方法来绘制误差线,由于某种原因,该方法没有得到很好的记录。基本上你只需要使用 stat='summary' 到 geom_errorbar 对象。

ggplot(data=mtcars, aes(x=gear, y=hp)) + geom_bar(stat='summary') + geom_errorbar(stat='summary', width=.2)

这是真的,如果您只想使用误差条来描述条形两侧的标准偏差(您可能希望使用不同的度量,如置信区间等)


推荐阅读