2017-09-13 175 views
1

如何使用ggplot.qplot將兩個帶誤差線的圖放在一個圖上。如何使用R繪製帶誤差線的兩條曲線ggplot2.qplot

我將它儘可能繪製一個圖形使用this後誤差條:

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

主要生產: enter image description here

我如何可以繪製處理數據放在同一個畫布上?

回答

2

注意我調整了給定的矢量來創建數據幀。

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

+0

謝謝!你能否在最後的代碼塊中放置一兩個評論來解釋代碼的功能背後的邏輯? – CiaranWelsh

+1

爲「dplyr」和「tidyr」使用添加了註釋。 '%>%'來自用於管理數據幀操作的'magrittr'。 – mrbcuda

+0

忽略提及,您可以使用'+ geom_point()'在錯誤欄內添加點。 – mrbcuda