【问题标题】:How to plot two curves with error bars using R ggplot2.qplot如何使用 R ggplot2.qplot 绘制两条带有误差线的曲线
【发布时间】:2018-02-22 17:03:52
【问题描述】:

如何使用ggplot.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))

产生:

如何在同一画布上绘制处理后的数据?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    注意我调整了给定的向量来创建数据框。

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

    【讨论】:

    • 谢谢!您能否在最后的代码块中添加一两条评论,解释代码所做的逻辑背后的逻辑?
    • dplyrtidyr 用法添加了 cmets。 %&gt;% 来自 magrittr,用于管道数据帧操作。
    • 忽略了,你可以使用+geom_point()在错误栏中添加点。
    猜你喜欢
    • 1970-01-01
    • 2016-08-06
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    相关资源
    最近更新 更多