Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 25, 2022 05:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/7d7e99d8f5fb623f7849 to your computer and use it in GitHub Desktop.
Save komasaru/7d7e99d8f5fb623f7849 to your computer and use it in GitHub Desktop.
R script to generate a choropleth map of Japan's population density.
# ライブラリの読み込み
library(gpclib)
library(ggplot2)
library(maptools)
library(classInt)
library(RColorBrewer)
# gpclib ライセンス警告表示の抑止
gpclibPermit()
# ==== 各種定数
TITLE <- "都道府県別人口密度" # <= グラフタイトル
TITLE_L <- "人口密度" # <= 凡例タイトル
CNT_DIV <- 8 # <= 凡例分割数
UNIT <- "人/km2" # <= 単位
STR_COPY <- paste(
"(地図出典:国土地理院・地球地図日本(行政界データ))",
"(データ出典:総務省統計局・平成22年国勢調査)",
"© 2014 mk-mode.com",
sep = "\n"
) # <= コピーライト用文字列
FILE_SHP <- "/path/to/polbnda_jpn_pref.shp" # <= Shapefile のフルパス
FILE_CSV <- "population_density_pref.csv" # <= CSV ファイル
FILE_SAV <- "population_density_pref.png" # <= 保存ファイル
# ==== Shapefile の読み込み
shp <- readShapePoly(FILE_SHP, IDvar = "pref_name")
# ==== CSV データ読み込み
csv <- read.csv(FILE_CSV, sep = ",", h = T)
# ==== 都道府県名でマッチング
pref.match <- match(shp$pref_name, csv$PREF_NAME)
dat <- csv[pref.match,]
# ==== 分類
klass <- classIntervals(dat$VALUE, n = CNT_DIV, style = "quantile")
divs <- klass$brks # <= 凡例ラベル用
rank <- findInterval(klass$var, klass$brks)
rank[rank[] == CNT_DIV + 1] <- CNT_DIV
# ==== 凡例用ラベル設定
label_l <- paste(divs, "〜")
# ==== Shapefile とデータの結合
dat_2 <- spCbind(shp, rank)
# ==== データフレーム形式に変換
df <- fortify(dat_2, region = "rank")
# ==== 地図 Plot
g <- ggplot(df) # <= オブジェクト生成
g <- g + ggtitle(TITLE) # <= グラフタイトル
g <- g + geom_polygon(
aes(long, lat, group = group, fill = id)
) # <= 地図描画
g <- g + scale_fill_brewer(
name = paste(TITLE_L, "\n(単位:", UNIT, ")"),
palette = "Blues",
labels = label_l
) # <= 凡例設定
g <- g + geom_path(
data = shp,
aes(long, lat, group = group),
colour = "black",
size = 0.3
)
g <- g + xlim(c(123.0, 150.0))
g <- g + ylim(c(23.0, 45.7))
g <- g + coord_equal() # <= メモリ刻み等間隔
g <- g + labs(x = STR_COPY, y = "") # <= x, y 軸ラベル無し
g <- g + theme(
plot.background = element_rect(
fill = "grey80",
colour = "black",
size = 0.5
)
) # <= プロット領域背景
g <- g + theme(
title = element_text(size = 10, colour = "black"), # <= タイトルのサイズ・色
axis.title.y = element_blank(), # <= y 軸ラベル非表示
axis.title.x = element_text(size = 7, colour = "gray20") # <= x 軸ラベルのサイズ・色
)
g <- g + theme(
panel.background = element_rect(
fill = "lightsteelblue",
colour = "black",
size = 0.2,
linetype = 1
)
) # <= グラフ枠・背景
# ==== 画像保存
ggsave(
file = FILE_SAV,
dpi = 100, width = 6.4, height = 6.4,
g
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment