错误栏在 barplot 上未正确绘制

Error bars not plotting correctly on barplot

我无法正确绘制误差线。这是我的数据框:

> d
         Date Plate.1 Plate.2 Plate.3 Plate.4 Plate.5 Plate.6 Plate.7 Plate.8 Sum Average        SE Treatment
1  2014-10-15       2       2       0       5       8      11      11       0  39   4.875 1.6304852         1
2  2014-11-12       5       4      11       6       7       2       9       6  50   6.250 0.9955257         1
3  2014-12-11       1       0       0       0       0       0       0       1   2   0.250 0.1636634         1
4  2015-02-11       0       0       4       0       2       1       0       1   8   1.000 0.5000000         1
5  2015-03-09       0       0       0       0       0       0       0       0   0   0.000 0.0000000         1
6  2014-10-15      30      22      24      19      10      16      19      42 182  22.750 3.4369318         2
7  2014-11-12       8       5       4       9      12      23      14      10  85  10.625 2.1207942         2
8  2014-12-11       0       5      21      19       2       9       4       0  60   7.500 2.9215945         2
9  2015-02-11      16      11       5       8       5      17       0       0  62   7.750 2.3126207         2
10 2015-03-09       0       0       0       1       0       0       0       0   1   0.125 0.1250000         2

我正在使用此代码生成分组条形图:

ggplot(d, aes(x=Date, y=Average, fill = Treatment)) +
  geom_bar(position="dodge", stat="identity") +
  geom_errorbar(aes(ymin=Average-SE, ymax=Average+SE),
                width=.2,                    
                position = position_dodge(.9))

由于某种原因,误差线绘制不正确,图表如下所示:

希望解决方案是一个简单的解决方案,但它让我望而却步。在此先感谢您的帮助!

根据您的评论进行了更新 - 对于此类绘图,您可以将 position_dodge 的值分配给一个变量,并将其用于所有后续绘图。 我通过一些试验和错误找到了 20 的值;如果您正在处理的其他数据在数值上有很大不同,您可能需要对此进行微调。

d <- data.frame(Date=c("2014-10-15", "2014-11-12", "2014-12-11",
                "2015-02-11", "2015-03-09", "2014-10-15",
                "2014-11-12", "2014-12-11", "2015-02-11",
                "2015-03-09"),
                Average=c(4.875, 6.250, 0.25, 1, 0,
                22.75, 10.625, 7.5, 7.75, 0.125),
                Treatment=c(rep(1, 5), rep(2, 5)),
                SE=c(1.6304852, 0.9955257, 0.1636634, 0.5, 0,
                3.4369318, 2.1207942, 2.9215945, 2.3126207, 0.125))
d$Date <- as.Date(d$Date)
d$Treatment <- factor(d$Treatment)
library(ggplot2)
pd1 <- 20
ggplot(d, aes(x=Date, y=Average, fill=Treatment)) + 
    geom_bar(width=pd1,
             position=position_dodge(pd1),
             stat="identity") +
    geom_errorbar(aes(ymin=Average-SE, ymax=Average+SE),
                  width=pd1 / 2,                    
                  position=position_dodge(pd1))

给予:

我认为您遇到的问题是使用 position="dodge" 允许 ggplot2 计算 'optimal' 闪避。但是,您需要 see/state 明确地将值作为参数传递给 geom_errorbar.

geom_bar 中的 width 设置为与 geom_bargeom_errorbar 中的 position_dodge 相同的值(此处为 pd1 <- 20)克服这个。