Reputation: 245
I have the below data visualisation for life expectancy of Asia using gapminder data-set, How can I change the plot to order it based on countries with higher life expectancy downwards?
Here is my code :
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)")
Upvotes: 2
Views: 525
Reputation: 3504
You could create a column with the age mean by country and then sort the levels of the factor country
based on the age mean values e.g.:
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)
Upvotes: 3