animationパッケージでHans Roslingのアレを再現する
TEDっていういろんな人が思い思いにプレゼンする集まりがある。
その中でもHans Roslingって統計学者がやったプレゼンは結構有名。
で、彼が使ったツールはGap minderという名称で公開されており、その後Googleにも買収されてGoogleドキュメントのSpreadsheetの中でMotion chartとして実装されている。
http://www.gapminder.org/
RからもgoogleVisパッケージを使えばMotion chartは作れるのだがいかんせんネット環境がないと使えない。
http://takahashik.blogspot.com/2011/01/googlevis-example.html
そんな感じでなんかローカルでも使えるものないかなーと探してたらanimationパッケージに実装されてるのを見つけた。
その名もRosling.bubblesとそのまんま。
実際に作ってみるとこんな感じになる。
データはgapminderのサイトからとってきた。
http://www.gapminder.org/data/
各データの名称は以下の3つで適宜csvに加工している。
Population, total→pop.csv
life expectancy(years)→life.csv
Children per woman(total fertillity)→birth.csv
以下コード。
library(animation) library(plyr) pop <- read.csv("pop.csv", as.is=TRUE) life <- read.csv("life.csv", as.is=TRUE) birth <- read.csv("birth.csv", as.is=TRUE) head(pop) head(life) head(birth) pop.m <- melt(pop) life.m <- melt(life) birth.m <- melt(birth) pop.m$variable <- as.numeric(gsub("X", "", pop.m$variable )) life.m$variable <- as.numeric(gsub("X", "", life.m$variable )) birth.m$variable <- as.numeric(gsub("X", "", birth.m$variable )) #1961-2009までのデータを用いる pop.m <- subset(pop.m, variable>=1961 & variable<=2009) life.m <- subset(life.m, variable>=1961 & variable<=2009) birth.m <- subset(birth.m, variable>=1961 & variable<=2009) colnames(pop.m) <- c("country", "year", "population") colnames(life.m) <- c("country", "year", "lifeexpectancy") colnames(birth.m) <- c("country", "year", "birthrate") df <- merge(merge(pop.m, life.m), birth.m) df <- df[order(df$year),] #GIFアニメ作成(ImageMagickが必要、convertのパス指定は場合によってはいらないかも) saveMovie(Rosling.bubbles(x=df[,5], y=df[,4], circles=df[,3], text = 1961:2009, text.cex=10, xlim=range(df[,5], na.rm=TRUE), ylim=range(df[,4], na.rm=TRUE), main="Hans Rosling's dynamic motion chart", xlab="Fertility rate", ylab="Life expectancy"), interval=0.5, convert = "/opt/local/bin/convert")