Skip to content

Instantly share code, notes, and snippets.

@ilarischeinin
Last active November 23, 2016 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilarischeinin/422decdf8c6eaa5fbfb6 to your computer and use it in GitHub Desktop.
Save ilarischeinin/422decdf8c6eaa5fbfb6 to your computer and use it in GitHub Desktop.
library(pxweb)
library(dplyr)
library(stringr)
library(ggplot2)
library(animation)
api <- "http://pxnet2.stat.fi/PXWeb/api/v1/"
past_original <- get_pxweb_data(
url=paste0(api, "en/StatFin/vrm/vaerak/125_vaerak_tau_106.px"),
dims=list(Vuosi="*", Sukupuoli="*", Ikä="*"),
clean=TRUE)
future_original <- get_pxweb_data(
url=paste0(api, "en/StatFin/vrm/vaenn/010_vaenn_tau_101.px"),
dims=list(Vuosi="*", Sukupuoli="*", Ikä="*"),
clean=TRUE)
past <- past_original %>%
filter(!str_detect(Age, "total"), Sex != "Both sexes") %>%
transmute(
year=as.integer(as.character(Year)),
age=as.integer(gsub("[^0-9]", "", Age)),
sex=tolower(as.character(Sex)),
population=values
) %>%
tbl_df()
future <- future_original %>%
filter(!Year %in% unique(past$year)) %>%
filter(!str_detect(Age, "total"), Sex != "Both sexes") %>%
transmute(
year=as.integer(as.character(Year)),
age=as.integer(gsub("[^0-9]", "", Age)),
sex=tolower(as.character(Sex)),
population=values
) %>%
tbl_df()
both <- rbind(past, future)
both$population[both$sex == "males"] <-
-both$population[both$sex == "males"]
years <- sort(unique(both$year))
titles <- paste("Population Structure of Finland,", years)
titles <- ifelse(years %in% unique(past$year), titles,
paste(titles, "(forecast)"))
saveGIF({
for (i in seq_along(years)) {
year_data <- filter(both, year == years[i])
p <- ggplot(year_data, aes(age, population, fill=sex, width=1)) +
coord_flip() +
geom_bar(data=filter(year_data, sex == "females"), stat="identity") +
geom_bar(data=filter(year_data, sex == "males"), stat="identity") +
scale_y_continuous(breaks=seq(-50e3, 50e3, 25e3),
labels=format(abs(seq(-50e3, 50e3, 25e3)), trim=TRUE, big.mark=" "),
limits=c(-50e3, 50e3)) +
theme(text=element_text(size=16),
legend.position="bottom", legend.title=element_blank(),
legend.background=element_rect(fill="#9ecae1"),
legend.key=element_rect(fill=NA, color=NA),
panel.background=element_rect(fill="#9ecae1"),
plot.background=element_rect(fill="#9ecae1")) +
scale_fill_manual(values=c('#18447e', '#ffffff')) +
guides(fill=guide_legend(reverse=TRUE)) +
labs(title=titles[i]) +
annotate("text", x=100, y=50e3, hjust=1.05, vjust=1.1,
label="By: Ilari Scheinin\nSource: Statistics Finland\nLicense: CC BY")
print(p)
}
}, movie.name="finland-population-structure.gif",
interval=0.25, ani.width=800, ani.height=600)
# Modified from:
# https://gist.github.com/walkerke/f9665e15b74b393bd2d6
# 2016-02-27
# Ilari Scheinin
# CC BY
# EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment