【问题标题】:How to add error bars with standard deviation using ggplot2如何使用ggplot2添加具有标准偏差的误差线
【发布时间】:2019-05-02 09:51:13
【问题描述】:

我想在我的线性图上绘制带有标准偏差的误差线。我不知道为什么它只使用标准错误。我做错了什么?

我尝试了几种方法,但总是出错。

library(ggplot2)
line = ggplot(alldata, aes(Time, Vol))
line +
  stat_summary(fun.y = mean, geom = 'point')+
  stat_summary(fun.y = mean, geom = "line", aes(group = 1))+
  stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.5)+

当它是 mean_se 时,它正在工作,但我需要 sd

  ylab("V")+
  xlab("T)")+
  theme_bw()+
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.background = element_rect(colour = "black", size=2))
  • 时间-x
  • alldata - 数据框

我有我的情节,但只有标准误差线

【问题讨论】:

    标签: r ggplot2 standard-deviation


    【解决方案1】:

    欢迎来到 SO。请参阅here,了解如何创建最小的可重现示例。从中学习并修改您的问题。除此之外,一个很好的问题是反映已完成充分研究的问题。之前提出的类似问题并不缺乏。因此,当您发布问题时,请确保提供足够的文档说明您尝试过的所有步骤,包括类似的问题,以找到您的解决方案。

    在没有数据的情况下,我使用mtcars 数据集。

    mean_sdl 接受一个参数mult,它指定标准偏差的数量 - 默认情况下它是mult = 2。所以需要通过mult = 1

    library(tidyverse)
    
    #load mtcars dataset
    mtcars <- mtcars
    str(mtcars)
    # coerce to factor for bar plot
    mtcars$cyl<- as.factor(mtcars$cyl)
    mtcars$gear<- as.factor(mtcars$gear)
    
    ggplot(mtcars, aes(cyl, disp, fill = gear)) +
      geom_bar(stat = "summary", fun.y = "mean", na.rm = TRUE,
           position = position_dodge(width = 0.9)) +
      geom_errorbar(stat = "summary", fun.data = "mean_sdl", 
                fun.args = list(mult = 1),
                position =  position_dodge(width = 0.9)) +
      ylab("mean displacement") +
      ggtitle("Some plot")
    

    【讨论】:

    • 谢谢!有效。这是我的第一个问题,下次我会改进。
    • @daria-cislo,如果建议的解决方案对您有用,则接受它作为答案。这将有助于其他人查看此问题。
    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2012-10-26
    相关资源
    最近更新 更多