简体   繁体   English

R ggplot2 绘制组均值的条形图

[英]R ggplot2 to plot bars for group mean

I'm using the dataset from the package "gapminder" which has a variable "continent" and a variable "lifeExp" (life expectancy).我正在使用“gapminder”包中的数据集,它有一个变量“大陆”和一个变量“lifeExp”(预期寿命)。 I used -mutate- function to calculate the mean and sd of lifeExp for each continent and add this variable into the dataset (so each observation will have a mean of lifeExp), it will be like this: 1 When I want to use -ggplot2- package to plot bars of means of "lifeExp" (variable "mean") by "continent", it seems that R will sum up the value of "mean" like this: 2我使用 -mutate- 函数计算每个大陆的 lifeExp 的均值和 sd 并将此变量添加到数据集中(因此每个观察都会有一个 lifeExp 的均值),它将是这样的: 1当我想使用 -ggplot2 - 通过“大陆”绘制“lifeExp”(变量“mean”)均值条的包,似乎R会像这样总结“mean”的值: 2

My code is:我的代码是:

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")

How to plot in group level of mean not summing up the mean?如何在均值的组级别绘制而不是对均值求和? Thank you!谢谢!

It appears that you calculated the means of lifeExp by country , then you plotted those values by continent .看来您是按country计算了lifeExp ,然后按continent绘制了这些值。 The easiest solution is to get the data right before ggplot , by calculating mean and sd values by 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")

Created on 2020-01-16 by the reprex package (v0.3.0)reprex 包(v0.3.0) 于 2020 年 1 月 16 日创建

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

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