Search code examples
rggplot2graphgeom-bar

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


I have a dataset I'm plotting with ggplot - and I'm running into an issue with replicate variables. Occasionally we made duplicates runs of the same method and I would like to have them plotted separately rather than seeing the largest with overlaid error bars. Is there anyway to work around this? This is what it currently looks like - notice the error bars in the middle. In other words, instead of just 5 bars I'd like to see the total 9.

My code looks like this:

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

The dataframe DF looks like this:

    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

Solution

  • You can try this. Please check if this is what you want (Updated):

    #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)
    

    enter image description here