【问题标题】:Plotting two sets of mean and standard deviation (using errbar)绘制两组均值和标准差(使用 errbar)
【发布时间】:2016-01-14 16:44:03
【问题描述】:

我使用errbar 在 R 中生成了一个显示均值和标准差的图形。

这是我的代码

errbar(data$Type, data$Mean,data$Mean+data$Std,data$Mean-data$Std,
       xlab="Type",ylab="Score", ylim=c(0,10))

生成均值和标准差(水平)图:

我想生成一个图,其中对于每个“类型”(类别),图上显示的均值/标准不止一个。所以我想要的情节看起来像这样(或每个类别有多个数据点):

我可以使用errbar 函数来执行此操作吗?如果不是,您建议如何在 R 中执行此操作?

这是 dput(data) 的输出:

structure(list(Type = structure(c(8L, 5L, 7L, 2L, 1L, 6L, 3L, 4L), 
          .Label = c("A", "B", "C", "D", "E", "G", "H", "R"), 
          class = "factor"), Mean = c(5.26785714285714, 5.41071428571429, 5.92857142857143, 
               6.23333333333333, 6.3, 7.78571428571429, 8.38333333333333, 8.75), 
          Std = c(2.3441094046778, 1.80971508291186, 1.50457178749844, 1.86716617466403, 1.93233759251032, 
               1.3931740974961, 1.06848802832164, 1.00445436503037)), 
          .Names = c("Type", "Mean", "Std"), 
          row.names = c(8L, 5L, 7L, 2L, 1L, 6L, 3L, 4L), class = "data.frame")

【问题讨论】:

    标签: r plot mean standard-deviation


    【解决方案1】:

    这是ggplot2 方法。首先,将以下内容添加到您发布的数据框中:

    Mean 对数据框进行排序,然后通过转换为因子来锁定该顺序:

    data = data[order(data$Mean),]
    data$Type = factor(data$Type, levels=data$Type)
    

    在数据框中再添加两行,这样我们就可以为每个Type 绘制多个均值/误差条:

    data = rbind(data, data.frame(Type=c("R","E"), Mean=c(0.5,1.2), Std=c(1.4,1.7)))
    

    添加一个分组变量,以便为给定的Type 绘制不同颜色的多个值:

    data$group = c(rep("Group 1",8), rep("Group 2", 2))
    

    现在开始剧情:

    ggplot(data, aes(x=Type, Mean, colour=group)) +
      geom_errorbar(aes(ymax=Mean+Std, ymin=Mean-Std), width=0) +
      geom_point(size=3) +
      coord_flip() +
      theme_grey(base_size=15) +
      guides(colour=FALSE)
    

    通过使用分组变量,您还可以“躲避”给定Type 内的点的位置,如果误差条与给定的Type 值重叠,这将很有用。例如:

    # Add another row to the data
    data = rbind(data, data.frame(Type="G", Mean=7.5, Std=1.5, group="Group 2"))
    
    # Dodging function
    pd = position_dodge(width=0.5)
    
    ggplot(data, aes(x=Type, Mean, colour=group)) +
      geom_errorbar(aes(ymax=Mean+Std, ymin=Mean-Std), width=0, position=pd) +
      geom_point(size=3, position=pd) +
      coord_flip() +
      theme_grey(base_size=15) +
      guides(colour=FALSE)
    

    【讨论】:

    • 谢谢 - 这真的很有帮助。
    • 我也可以问一下,有谁知道如何强制这样一个情节的轴在 0 到 10 之间?我尝试了一些东西,例如 ylim = c(0,10),但没有成功。
    • 添加scale_y_continuous(limits=c(0,10))。请注意,如果任何数据超出这些限制,ggplot2 将排除它(带有警告)。要设置小于数据范围而不排除任何数据的限制,请使用coord_cartesian(ylim=c(0,10))
    猜你喜欢
    • 2014-08-28
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 2018-02-25
    • 2019-07-24
    • 1970-01-01
    • 2017-04-01
    • 2012-07-17
    相关资源
    最近更新 更多