Last active
January 15, 2018 19:44
-
-
Save bhive01/3e8676c2415bae3c6b1c0c602fcf853c to your computer and use it in GitHub Desktop.
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(tidyverse) | |
library(animation) | |
library(tweenr) | |
library(gtools) | |
income <- read_csv("income.csv") | |
income_levels <- mixedsort(unique(income$income_level)) | |
income_levels <- c(income_levels[16], income_levels[1:15]) | |
income <- income %>% mutate(income_level=factor(income_level, | |
levels=income_levels)) | |
census_regions <- read_csv("https://raw.githubusercontent.com/cphalpert/census-regions/master/us%20census%20bureau%20regions%20and%20divisions.csv") | |
combined_frame <- income %>% inner_join(census_regions, by=c('state' = 'State')) | |
visualization_frame <- | |
combined_frame %>% | |
group_by(year, Region, income_level) %>% | |
summarise(percent_of_total = mean(percent_of_total)) %>% | |
ungroup() | |
mylist <- | |
visualization_frame %>% | |
mutate(year2 = year, Region = as_factor(Region)) %>% | |
nest(-year) %>% | |
pull(data) | |
tween.df <- tween_states(mylist | |
,tweenlength = 1 | |
,statelength = 2 | |
,ease = 'cubic-in-out' | |
,nframes=121) | |
myplot<-function(i){ | |
g <- | |
ggplot(data = filter(tween.df, i==.frame) | |
, aes(x = income_level, y = percent_of_total, fill = Region) | |
) + | |
geom_bar(stat="identity", position="stack") + | |
theme_minimal() + | |
theme(axis.text.x = element_text(angle = 45, hjust = 1)) + | |
ggtitle("Distribution by Income Level", "by % of total state population") + | |
xlab("") + | |
ylab("% of Population") | |
return(g) | |
} | |
oopt = ani.options(interval = 0.1) | |
saveGIF({for (i in seq_along(unique(tween.df$.frame))) { | |
g <- myplot(i) | |
print(g) | |
print(i) | |
ani.pause() | |
} | |
}, movie.name="incomedata_tween.gif", ani.width = 600, ani.height = 600) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment