繁体   English   中英

R ggplot2 绘制组均值的条形图

[英]R ggplot2 to plot bars for group mean

我正在使用“gapminder”包中的数据集,它有一个变量“大陆”和一个变量“lifeExp”(预期寿命)。 我使用 -mutate- 函数计算每个大陆的 lifeExp 的均值和 sd 并将此变量添加到数据集中(因此每个观察都会有一个 lifeExp 的均值),它将是这样的: 1当我想使用 -ggplot2 - 通过“大陆”绘制“lifeExp”(变量“mean”)均值条的包,似乎R会像这样总结“mean”的值: 2

我的代码是:

gap2007 %>%
  ggplot(., aes(x=continent, y=mean, fill=continent))+
  geom_bar(stat='identity')+
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd))+
  xlab("Continent") + ylab("Mean life expectancy") +
  labs(title="Barplot of Average Life Expectancy with Standard Deviations")

如何在均值的组级别绘制而不是对均值求和? 谢谢!

看来您是按country计算了lifeExp ,然后按continent绘制了这些值。 最简单的解决方案是在ggplot之前获取数据,通过按continent计算meansd值:

library(tidyverse)
library(gapminder)

df<-gapminder %>% 
  group_by(continent) %>% 
  summarize(
    mean = mean(lifeExp), 
    median = median(lifeExp), 
    sd = sd(lifeExp)
  ) 

df %>%
  ggplot(., aes(x=continent, y=mean, fill=continent))+
  geom_bar(stat = "identity")+
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd))+
  xlab("Continent") + ylab("Mean life expectancy") +
  labs(title="Barplot of Average Life Expectancy with Standard Deviations")

reprex 包(v0.3.0) 于 2020 年 1 月 16 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM