2017-09-13 3 views
1

ggplot.qplot을 사용하여 하나의 그래프에 오차 막대가있는 두 개의 그래프를 어떻게 배치 할 수 있습니까? enter image description hereR ggplot2.qplot을 사용하여 오차 막대가있는 두 곡선을 그리는 방법

가 어떻게 같은 캔버스에 처리 된 데이터를 플롯 할 수 있습니다 : 생산

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

:

나는 지금까지 this 포스트를 사용하여 오차 막대 하나 개, 그래프 만들었어요?

답변

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

관련 문제