如何防止 geom_bar 中的条与同一个变量重叠?

How to prevent the bars in geom_bar from overlapping with the same variable?

我有一个正在使用 ggplot 绘制的数据集 - 我 运行 遇到了复制变量的问题。有时我们会重复运行相同的方法,我希望将它们分开绘制,而不是看到最大的重叠误差条。有什么办法可以解决这个问题吗? This is what it currently looks like - notice the error bars in the middle。换句话说,我希望看到总共 9 个而不是 5 个。

我的代码如下所示:

totPlot <- ggplot(data=DF, aes(x=Sample, y=Obs.Age, fill = Method)) + 
  geom_bar(stat="identity", position = "dodge", width = 0.8, colour = "black") + 
  xlab("Site and Sample No.") + 
  ylab("Age BP") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
  geom_errorbar(aes(ymin = obs.Lower, ymax = obs.Upper), width = 0.2, 
                position = position_dodge(0.8), colour = "black") + 
  geom_hline(yintercept = 0) + 
totPlot

数据框 DF 如下所示:

    Sample   Number         Method   Obs.Age  obs.Upper  obs.Lower
1   F_RC_P1   6184         CHM_ABA     364       383       345
2   F_RC_P1   6185         CHM_ABA     362       381       343
3   F_RC_P1   6186         CHM_ABA    1316      1339      1293
4   F_RC_P1   6184      A_Expected     365       385       345
5 K_WS_NN14-5 6500 UrVFD_PUCHM_ABA    1120      1150      1090
6 K_WS_NN14-5 6182         CHM_ABA     687       706       668
7 K_WS_NN14-5 6183         CHM_ABA    1058      1077      1039
8 K_WS_NN14-5 6500      A_Expected     365       385       345
9 K_WS_NN14-5 6182      A_Expected     690       710       670

你可以试试这个。请检查这是否是您想要的(更新):

#Create vector of labels
veclabs <- DF[order(DF$Obs.Age),'Sample']
#Plot
ggplot(data=DF %>% mutate(Number2=paste(Number,1:dim(DF)[1])),
       aes(x=reorder(interaction(Sample,Number2),Obs.Age), y=Obs.Age, fill = Method)) + 
  geom_bar(stat="identity", position = "dodge", width = 0.8, colour = "black") + 
  xlab("Site and Sample No.") + 
  ylab("Age BP") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
  geom_errorbar(aes(ymin = obs.Lower, ymax = obs.Upper), width = 0.2, 
                position = position_dodge(0.8), colour = "black") + 
  geom_hline(yintercept = 0)+
  scale_x_discrete(labels = veclabs)