在 Iris 数据集中查找均值和标准差并绘制图形

Find mean and sd in Iris data set and draw graph

我需要按物种查找 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) 

ggplot默认不允许误差线堆叠。所以,你必须手动完成 error bar with stacked barplot which is not that good. If you want to implement it you can follow ,否则你可以使用类似

的东西
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")