【问题标题】:Plot Grouped bar graph with calculated standard deviation in ggplot在ggplot中绘制具有计算标准偏差的分组条形图
【发布时间】:2018-05-18 15:30:16
【问题描述】:

我觉得这应该很容易做到,但我很难弄清楚这一点。

我有一个数据框

type <- c("a","b","c","d","e")
x <- rnorm(5)
y <- rnorm(5)
z <- rnorm(5) 
xsd <- sd(x)
ysd <- sd(y)
zsd <- sd(z)
df <- data.frame(type, x,y,z,xsd,ysd,zsd)
df



type           x          y         z       xsd       ysd       zsd
1    a -1.16788106  0.2260430 -1.16788106 0.8182508 0.7321015 0.9016335
2    b -0.09955193 -0.6647980 -0.09955193 0.8182508 0.7321015 0.9016335
3    c -0.87901053 -0.4269936 -0.87901053 0.8182508 0.7321015 0.9016335
4    d -0.87861339 -1.3669793 -0.87861339 0.8182508 0.7321015 0.9016335
5    e  0.84350228  0.4702580  0.84350228 0.8182508 0.7321015 0.9016335

我需要typexyz 平均值的分组条形图,其中误差线显示每个变量的标准偏差。标准差在不同的列xsd,ysdzsd

我需要在 y 轴上绘制平均值,type 在 x 轴上对 xyz 变量进行分组。 我尝试使用gather() 重新排列数据,但没有任何成功...

【问题讨论】:

  • x、y、z 是条形本身的值吗?或者你想绘制平均值?您预计 15 条还是 3 条?
  • 你的真实数据集是这样的吗?
  • @AntoniosK 是的,不同的名称,但非常相似。只是为了重现性和可读性重新创建了它。

标签: r ggplot2


【解决方案1】:

让ggplot2为你做计算:

install.packages("hmisc") # for mean_sdl

library(tidyverse)

type <- c("a","b","c","d","e")
x <- rnorm(5, 10, 5)
y <- rnorm(5, 8, 3)
z <- rnorm(5, 2, 4) 

df <- data.frame(type,x,y,z)

df_long <- df %>% 
  gather(variable, value, x:z)

ggplot(df_long, aes(x = variable, y = value, fill = variable)) + 
  stat_summary(fun.y = "mean", geom = "col") + 
  stat_summary(fun.data = mean_sdl, geom = "errorbar", width = .5, fun.args = list(mult = 1))

【讨论】:

  • 谢谢!我不知道 ggplot 可以为你做计算。这非常接近我的需要。我只需要将变量按type 分组
  • “按类型分组”是什么意思?类型应该在 x 轴上吗?
  • 变量typec("a","b","c","d","e")。是的,它应该对 x、y 和 z 变量进行分组
  • 那你会有15个吧?这没有任何意义,您只有 15 个观察值,因此您无法获得单个观察值的标准差。
  • 你是完全正确的。我意识到我最初的评论并不能完全代表我的数据。然而,我能够用我的真实数据做我需要的事情。
【解决方案2】:

这个例子应该会有所帮助:

type <- c("a","b","c","d","e")
x <- rnorm(50,20, 5)
y <- rnorm(50, 25,1)
z <- rnorm(50, 40, 1) 

df <- data.frame(type, x,y,z)
df

library(tidyverse)

df %>%
  gather(x,value,-type) %>%
  group_by(type, x) %>%
  summarise(MEAN = mean(value),
            SD = sd(value)) %>%
  ggplot(aes(x, MEAN, fill=type))+
  geom_bar(stat="identity", position = "dodge")+
  geom_errorbar(aes(ymin=MEAN-SD, ymax=MEAN+SD), position = "dodge")

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多