【问题标题】:Find mean and sd in Iris data set and draw graph在 Iris 数据集中查找均值和标准差并绘制图形
【发布时间】:2021-07-01 23:53:53
【问题描述】:

我需要为 Iris 数据集中的每个数值变量找到物种的平均值和标准差,并使用 geom_col 和 geom_errorbar 在 ggplot2 图中绘制它。

这是我目前得到的

library(tidyverse)
data(Iris)
iris %>% 
  group_by(Species) %>% 
    summarise_if(is.numeric, list(mean = mean, sd = sd)) -> IrisData

我尝试创建图表,但不知道如何使用 geom_errorbar

IrisData %>%
  select(Species, ends_with("mean")) %>%
  gather(key, val, 2:5) %>%
  ggplot(aes(key, val, fill = Species)) +
  geom_col()

我发现它应该看起来像这样

geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd), width=0.2)

但我不确定如何使用它,我将其添加到代码末尾并得到了一些图表,但我确定它不正确

geom_errorbar(aes(ymin = val - sd(val), ymax = val + sd(val)), width=0.2, size = 1.2) 

【问题讨论】:

    标签: r ggplot2 mean standard-deviation


    【解决方案1】:

    ggplot 默认情况下不允许堆叠误差线。因此,您将不得不手动操作error bar with stacked barplot,这不是很好。如果你想实现它,你可以关注this,否则你可以使用类似

    library(tidyverse)
    data(iris)
    
    iris %>% 
      group_by(Species) %>% 
      summarise_if(is.numeric, list(mean = mean, sd = sd)) -> IrisData
    
    iris %>% 
      pivot_longer(-Species) %>% 
      group_by(Species, name) %>% 
      summarise(Mean = mean(value),  
                SD = sd(value)) -> IrisData
    
    IrisData %>%
      ggplot(aes(name, Mean, fill = Species)) +
      geom_bar(stat = "identity", position = "dodge")+
      geom_errorbar(aes(ymin = Mean - SD, ymax = Mean + SD), width=0.2, position = position_dodge(.9))
    

    library(ggpubr)
    iris %>% 
      pivot_longer(-Species) %>% 
      ggbarplot(x = "name", y = "value", add = "mean_sd",
      color = "Species")
    

    【讨论】:

      猜你喜欢
      • 2012-07-17
      • 2020-11-21
      • 2013-03-24
      • 2019-07-24
      • 2014-08-28
      • 1970-01-01
      • 2022-07-05
      • 2013-11-22
      • 2014-02-12
      相关资源
      最近更新 更多