[英]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
計算mean
和sd
值:
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.