我使用gapminder数据集对亚洲的预期寿命进行了以下数据可视化,如何根据预期寿命较长的国家更改图表进行订购?
这是我的代码:
install.packages("gapminder")
library(gapminder)
Asia_sample2 <- gapminder %>% filter (gapminder$continent =="Asia")
p1 <- ggplot(data = Asia_sample2, aes(x = year , y = country , fill = lifeExp ))
p1 + geom_raster() +scale_fill_gradient(low="blue", high="red") +
theme_bw() +
labs(title = "Estimated Life Expectancy in Asia , Years(1952-2007)")
答案 0 :(得分:3)
您可以按国家/地区创建一个年龄均值的列,然后根据年龄平均值对因子country
的级别进行排序,例如:
library(gapminder)
library(dplyr)
library(ggplot2)
Asia_sample2 <- gapminder %>% group_by(country) %>%
mutate(lifeExp_mean = mean(lifeExp)) %>% filter (continent =="Asia") %>%
arrange(lifeExp_mean) %>% ungroup()
Asia_sample2$country <- factor(Asia_sample2$country, levels=unique(Asia_sample2$country))
p1 <- ggplot(data = Asia_sample2, aes(x = year , y = country , fill = lifeExp ))
p1 + geom_raster() + scale_fill_gradient(low="blue", high="red") +
theme_bw() +
labs(title = "Estimated Life Expectency in Asia , Years(1952-2007)")
ggsave("plot.png", width = 10, height = 5)