偶然記起去年一位朋友微信發我一份花旗國大選資料,請教我如何畫動態統計圖,我抄起鍵盤改了改他的代碼跑通了,這份資料包含了1960-2012年花旗國歷次大選的投票人數(精確到縣級),我們使用map()函式就能很容易地為地圖著色,
唯一創新的點在于我使用了viridis包里的調色盤資料,轉化成rgb顏色進行填充,這里本來準備按照慣例使用紅藍配色,但由于著色區域太多,顏色顯得很暗,故改為從黃色到藍色的色譜,
為了給每一幅圖片配上相應的圖例,我收集了每一任統領姓名、當選年份與對應社團的資訊,這些資訊被存在president.csv檔案里,然后繪制每幅圖的時候配上相應年份的資訊就行了,
library(maps)
library(animation)
library(viridis)
library(data.table)
setwd('E:/election_dy_plot')
election = fread('./elections.csv')
presidenten = fread('president.csv')
election[, `:=`(sharedem = dem / (rep + dem + other),
sharerep = rep / (rep + dem + other))]
data(viridis.map) # a viridis palette
setDT(viridis.map)
viridis.map = viridis.map[opt == 'C', ]
coldt = viridis.map[election[, sharerep * 250], ][, opt := NULL]
election[, county.col := rgb(coldt[, R], coldt[, G], coldt[, B])]
one = viridis.map[0.125 * 250, ]
two = viridis.map[0.375 * 250, ]
thre = viridis.map[0.625 * 250, ]
fo = viridis.map[0.875 * 250, ]
fi = rgb(one[, 1], one[, 2], one[, 3])
se = rgb(two[, 1], two[, 2], two[, 3])
thr = rgb(thre[, 1], thre[, 2], thre[, 3])
fr = rgb(fo[, 1], fo[, 2], fo[, 3])
colors = c(fr, thr, se, fi)
saveGIF({
for (i in seq(1960, 2012, 4)) {
# 1960-2012 loop every 4 year
thisyear = subset(election, year == i)
map(database = "county",
# plot by year
col = thisyear[,county.col],
fill = T)
tit = paste('United States Presidential Election:', i) # get every year title
title(tit, cex.main = 1.3) # Add title
sub = subset(presidenten, year == i)
ps = paste('Winner:', sub[, 2], '-', sub[, 3]) # get every year winner
mtext(ps, side = 1, cex = 1.1)
leg.txt = c("75-100%", "50-75%", "25-50%", "0-25%")
legend(
"bottomright",
leg.txt,
fill = colors,
title = ("Republican %"),
cex = 0.83
)
}
} , movie.name = "election_en.gif",
interval = 2) # set every plot stay time

如果將圖例和president.csv檔案改為中文,也可以畫出個中文版的:

注意,最后使用animation輸出gif圖片需要安裝ImageMagick,具體方法上網搜肯定能解決,時間太久遠記不得怎么弄了,
最近作業中很少用到R,但是R的一些可視化功能仍然強大,這篇就算做個歸檔吧,
文中使用的資料,點擊下載,

掃碼關注公眾號ApocalypseNow,分享好玩的資料分析
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/223051.html
標籤:其他
上一篇:編譯原理(4)——自增自減
