One directional error bars in ggplot2

2019-08-15 13:00发布

问题:

I am plotting some data from a test that was repeated pre and post an intervention. As such I would like to plot the results on the same figure with error bars. As the error bars of the two trials cross, making it difficult to decipher, I would like to plot the error bars upwards only for the post test and downwards only for the pre test. Is this possible in ggplot2?

Example code:

library("ggplot2")
set.seed(1)
dat <- data.frame(Trial = c(rep("Pre",9),rep("Post",9)), 
                  Time = rep.int(seq(0,120,15),2), 
                  Insulin = c(rnorm(9,15,2),rnorm(9,22,2)),
                  Insulin_sd = c(rnorm(18,3,1)))


p3 <- ggplot(data = dat, aes(x = Time, y = Insulin, group = Trial))+
  geom_errorbar(aes(ymin = Insulin - Insulin_sd, ymax = Insulin + Insulin_sd,linetype = Trial), width = 4) +
  geom_line(aes(linetype = Trial)) +
  geom_point(aes(shape= Trial, fill = Trial), size = 2) +
  scale_shape_manual(values=c(21,24),guide = guide_legend(reverse = TRUE)) +
  scale_fill_manual(values=c("black","white"),guide = guide_legend(reverse = TRUE)) +
  scale_linetype_manual(values = c("solid","dashed"),guide = guide_legend(reverse = TRUE)) +
  scale_y_continuous(limits= c(0,35))

(sorry- not able to upload an image)

Any help greatly appreciated.

回答1:

One way to get close to what you want is to manually set error bar maxima and minima using Boolean logic based on your existing data.

dat$min <- dat$Insulin - (dat$Trial=='Pre')*dat$Insulin_sd

dat$max <- dat$Insulin + (dat$Trial=='Post')*dat$Insulin_sd

p3 <- ggplot(data = dat, aes(x = Time, y = Insulin, group = Trial)) +
       geom_errorbar(aes(ymin=min, ymax=max, linetype = Trial), width = 4) +
       geom_line(aes(linetype = Trial)) +
       geom_point(aes(shape= Trial, fill = Trial), size=2) +
       scale_shape_manual(values=c(21,24), guide=guide_legend(reverse = TRUE)) +
       scale_fill_manual(values=c("black","white"), guide=
             guide_legend(reverse = TRUE)) +
       scale_linetype_manual(values = c("solid","dashed"), 
             guide=guide_legend(reverse = TRUE)) +
       scale_y_continuous(limits= c(0,35))



标签: r ggplot2