1

How can I put two graphs with error bars on one graph using ggplot.qplot.

I've made it as far plotting one graph with error bars using this post:

library(ggplot2)
time_points = c(15,  30,  60,  90, 120, 150, 180)
control_data = c(1,2,3,4,5,6,7)
control_sd = c(0,1, 0.2, 0.3, 0.4, 0.5, 0.6)


treated_data = c(9,8,7,6,5,4,3)
treated_sd = c(0,1, 0.4, 0.6, 0.8, 0.8, 0.9, 1.5)

qplot(time_points, control_data) + geom_errorbar(aes(x = time_points,
                                                 ymin = control_data - control_sd,
                                                 ymax = control_data + control_sd))

Which produces: enter image description here

How can I plot the treated data on on the same canvas?

Community
  • 1
  • 1
CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106

1 Answers1

2

Note I tweaked the given vectors to create the data frames.

library(ggplot2)
library(dplyr)
library(tidyr)
library(magrittr)

time_points = c(15,  30,  60,  90, 120, 150, 180)
control_data = c(1,2,3,4,5,6,7)
control_sd = c(0, 1, 0.2, 0.3, 0.4, 0.5, 0.6)

treated_data = c(9,8,7,6,5,4,3)
treated_sd = c(0.1, 0.4, 0.6, 0.8, 0.8, 0.9, 1.5)

df <- data.frame(time=time_points,
  cd=control_data,
  td=treated_data,
  csd=control_sd,
  tsd=treated_sd)

df %>%
  # stack the control and treated columns using tidyr's gather
  # from here we distinguish the different series by the type column
  gather(type,value,cd,td) %>% 
  # append a column for error bar ymin, depending on stacked type
  mutate(ymin=ifelse(type=='cd',value-csd,value-tsd)) %>% 
  # append a column for error bar ymax, depending on stacked type
  mutate(ymax=ifelse(type=='cd',value+csd,value+tsd)) %>%
  # pass the revised data frame to ggplot with the computed aesthetics
  ggplot(aes(x=time,y=value,color=type,ymin=ymin,ymax=ymax)) +
  geom_errorbar() +
  geom_point()

enter image description here

mrbcuda
  • 580
  • 7
  • 16
  • Thanks! Could you please put a comment or two in the final code block explaining the logic is behind what the code is doing? – CiaranWelsh Sep 13 '17 at 21:48
  • 1
    Added comments for the `dplyr` and `tidyr` usage. The `%>%` is from `magrittr` used to pipe the data frame manipulation. – mrbcuda Sep 14 '17 at 02:44
  • Neglected to mention you could add the points inside the error bars using `+geom_point()`. – mrbcuda Sep 14 '17 at 02:48