首页 > 解决方案 > GGPlot2:按条件分组的误差线

问题描述

使用这些数据:

condition <- c('control', 'control', 'causal', 'causal') # grouping condition
shift <- c('first', 'second') # subgrouping condition
means <- c(-30, 60, -20, 40) # means per group
se <- c(6, 10, 7, 9) # Standard errors per group
plotdata2 <- data.frame(condition, shift, means, se)

我想在下面的图中绘制误差线:

ggplot(plotdata2, aes(x=condition, y=means, fill=shift)) +
  geom_bar(stat='identity', width = .6) +
  coord_flip() 

在此处输入图像描述

但是,使用

ggplot(plotdata2, aes(x=condition, y=means, fill=shift)) +
  geom_bar(stat='identity', width = .6) +
  coord_flip() +
  geom_errorbar(aes(ymax = min(se)-0.5, ymin=max(se)+0.5))

在此处输入图像描述

不起作用,因为误差线采用 SE 的全局 ymax 和 ymin。如何使用各自条件的 min(se) 和 max(se) 制作两个不同的误差线?

我没有原始数据;因此,我只能使用此摘要。

标签: rggplot2

解决方案


您只是忘记sey = means.

ggplot(plotdata2, aes(x=condition, y=means, fill=shift)) +
  geom_bar(stat='identity', width = 0.6) +
  geom_errorbar(aes(ymax = means - se - 0.5, ymin = means + se + 0.5), width = 0.6) +
  coord_flip() 

在此处输入图像描述


推荐阅读