2017-08-13 21 views
2

我使用gapminder數據集對亞洲人的預期壽命進行了以下數據可視化,如何根據預期壽命較高的國家向下排列來更改圖來訂購它?R中的數據可視化,排序geom_raster()

這裏是我的代碼:

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

我正在使用R你只需要在下面做,你可以訪問gapminder install.packages(「gapminder」) library(gapm因德爾) –

回答

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) 

enter image description here