Last active
August 26, 2017 15:08
-
-
Save cavedave/80b92570caf3d217d0821441233e609f to your computer and use it in GitHub Desktop.
Animated heatmap of the world income and life expectancy. Original idea from NFL heatmap http://noahveltman.com/nflplayers/ I did one for NBA players https://gist.github.com/cavedave/21c6beff2d371e9df323c292b1dc3afa image at http://i.imgur.com/dobmMWM.gifv Image for this demographics at http://i.imgur.com/PvUS4Kr.gif
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(gapminder) | |
library(ggplot2) | |
library(devtools) | |
install_github("dgrtwo/gganimate") | |
library(gganimate) | |
library(dplyr) | |
mydata <- dplyr::select(gapminder, country,continent,year,lifeExp,pop,gdpPercap) | |
#bin years into 5 year bins | |
mydata$lifeExp2 <- as.integer(round((mydata$lifeExp-2)/5)*5) | |
mydata$income <- cut(mydata$gdpPercap, breaks=c(0,250,500,750,1000,1500,2000,2500,3000,3500,4500,5500,6500,7500,9000,11000,21000,31000,41000, 191000), | |
labels=c(0,250,500,750,1000,1500,2000,2500,3000,3500,4500,5500,6500,7500,9000,11000,21000,31000,'41000+')) | |
sizePer <- mydata%>% | |
group_by(lifeExp2, income, year)%>% | |
mutate(popLikeThis = sum(pop))%>% | |
group_by(year)%>% | |
mutate(totalPop = sum(as.numeric(pop)))%>% | |
mutate(per = (popLikeThis/totalPop)*100) | |
sizePer$percent <- cut(sizePer$per, breaks=c(0,.1,.3,1,2,3,5,10,20,Inf), | |
labels=c(0,.1,.3,1,2.0,3,5,10,'20+')) | |
saveGIF({ | |
for(i in c(1952,1957,1962,1967,1972,1977,1982,1987,1992,1997,2002,2007)){ | |
# for(i in c(1997,2002,2007)){ | |
print(ggplot(sizePer %>% filter(year == i), | |
aes(x = lifeExp2, y = income)) + | |
geom_tile(aes(fill = percent)) + | |
theme_bw()+ | |
scale_y_discrete(drop = F)+ | |
theme(legend.position="top", plot.title = element_text(size=30, face="bold",hjust = 0.5))+ | |
coord_cartesian(xlim = c(20,85), ylim = c(0,21)) + | |
scale_fill_manual("%",values = c("#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"),drop=FALSE)+ | |
annotate(x=80, y=3, geom="text", label=i, size = 7) + | |
annotate(x=80, y=1, geom="text", label="@iamreddave", size = 5) + | |
ylab("Income") + # Remove x-axis label | |
xlab("Life Expenctancy")+ | |
ggtitle("Worldwide Life Expectancy and Income") | |
) | |
} | |
}, interval=1.0,ani.width = 900, ani.height = 600) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment