How to plot two curves with error bars using R ggplot2.qplot -
how can put 2 graphs error bars on 1 graph using ggplot.qplot
.
i've made far plotting 1 graph 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))
how can plot treated data on on same canvas?
note tweaked given vectors create 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 control , treated columns using tidyr's gather # here distinguish different series type column gather(type,value,cd,td) %>% # append column error bar ymin, depending on stacked type mutate(ymin=ifelse(type=='cd',value-csd,value-tsd)) %>% # append column error bar ymax, depending on stacked type mutate(ymax=ifelse(type=='cd',value+csd,value+tsd)) %>% # pass revised data frame ggplot computed aesthetics ggplot(aes(x=time,y=value,color=type,ymin=ymin,ymax=ymax)) + geom_errorbar() + geom_point()
Comments
Post a Comment