我正在使用来自“ gapminder”软件包的数据集,该数据集具有变量“ continent”和变量“ lifeExp”(预期寿命)。我使用了-mutate-函数来计算每个大陆的lifeExp的平均值和sd,并将此变量添加到数据集中(因此每个观测值将具有lifeExp的平均值),就像这样: 1 当我想使用-ggplot2-包通过“ continent”来绘制“ 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")
如何在均值的分组水平上绘制而不求均值?谢谢!
答案 0 :(得分:0)
似乎您通过lifeExp
计算了country
的均值,然后通过continent
绘制了这些值。最简单的解决方案是通过ggplot
通过计算mean
和sd
的值来获取continent
之前的数据:
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 package(v0.3.0)于2020-01-16创建