Search code examples
rggplot2dplyrerrorbargeom-point

Rearranging order of X axis causes errorbars to no longer match up on y axis


I wanted to order my y axis values and in doing so my errorbars no longer fit on the y axis. The code is below if i run just ggplot down I get error bars in the right place, if I run it all removing the Kale_Nutrients from the ggplot the error bars are displaced on the Y axis.

Kale_Nutrients %>%
  arrange(X) %>%
  mutate(X = factor(X, levels=c( "Control", "B1 <2mm 5%", "B1 <2mm 10%", 
            "B1 <2mm 20%", "B1 >2mm 5%", "B1 >2mm 10%", 
            "B1 >2mm 20%", "B2 <2mm 5%", "B2 <2mm 10%","B2 <2mm 20%", "B2 >2mm 5%", "B2 >2mm 10%", "B2 >2mm 20%", "B3 <2mm 5%", "B3 <2mm 10%", "B3 <2mm 20%", "B3 >2mm 5%", "B3 >2mm 10%", "B3 >2mm 20%"))) %>%
ggplot(Kale_Nutrients,aes(X, P))+
geom_point()+
theme_classic()+
theme(axis.text.x=element_text(angle=90, size=12, color="black"),panel.grid.major = element_blank(), panel.grid.minor = element_blank(),panel.background = element_blank(),axis.line = element_line(colour = "black"),axis.text.y=element_text( size=14, color="black"),axis.title=element_text(size=14, face="bold"))+
geom_errorbar(ymin=Kale_Nutrients$P-Kale_Nutrients$P.s.e , ymax=Kale_Nutrients$P+Kale_Nutrients$P.s.e)+
ylim(0,4000)

Running without reordering the x axis

Running after reordering the x axis with the errorbars displaced on the y axis


Solution

  • You need to pull the values of the error bars from the dataset with the re-ordered factor levels, rather than the original Kale_Nutrients data frame. This would change your code for the error bars to something like:

    geom_errorbar(aes(ymin=P-P.s.e , ymax=P+P.s.e))+