2

我使用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)")
4

1 回答 1

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) 

在此处输入图像描述

于 2017-08-13T01:45:53.033 回答