library(ggthemes)
library(ggrepel)
library(httr)
library(jpndistrict)
library(sf)
library(tidyverse)jpndistrict パッケージをロードするremotes::install_github("uribo/jpndistrict")→ 都道府県別の地図データを抽出する
→ df_map_jpnという名前を付ける
df_jpn_map <- 1:47 %>%
map(~ jpn_pref(pref_code = ., district = FALSE)) %>%
reduce(rbind) %>%
st_simplify(dTolerance = 0.01)df_jpn_map の中身を確認し、東京都の pref_code を確認するDT::datatable(df_jpn_map)pref_code は 13→ 東京都の地図データ + 23区のみ抜き取る
df_tokyo_sf <- jpn_pref(13, district = TRUE) %>%
dplyr::filter(str_detect(city, "区")) # 23区だけを抜き取る設定df_tokyo_sf %>%
ggplot() +
geom_sf() +
theme_minimal()head(df_tokyo_sf, 23)city, geomety) だけに絞るdf_tokyo_sf <- df_tokyo_sf %>%
select(city, geometry)head(df_tokyo_sf, 23)e-Stat)にアクセスして手動でデータをダウンロードe-Stat)にアクセスして「アプリケーションID」を取得し自動でデータをダウンロードe-Stat からダウンロード(手動)【ダウンロードの範囲】から「ページ上部の選択項目(調査年)」を選ぶ
【ファイル形式】から「csv形式」を選ぶ
【ヘッダの出力】から「出力しない」を選ぶ
【コードの出力】から「出力しない」を選ぶ
✅️データがない行を表示しない
✅️データがない列を表示しない
→ 「ダウンロード」をクリック
→ 「ダウンロード」をクリック
→ ダウンロードした csv ファイルを開く
| 「調査年」 | → year |
| 「地域」 | → city |
| 「A1101_総人口【人】」 | → population |
city 内にある「東京都 」(東京都と半角スペース)を削除するcity 列を選び「編集」→「検索」→「置換」tokyo_pop.csvと名前をつけて保存(例えばデスクトップに)CSV UTF-8(コンマ区切り)(.csv)を指定e-Stat からダウンロード(自動)e-stat の API を利用して人口を取得するAPI やアプリケーション ID の取得方法やデータのダウンロードに関してはこちらを参照id <- "取得したアプリケーションIDをここに貼り付ける"get_estat <- GET(
url = "http://api.e-stat.go.jp", path = "rest/2.1/app/getSimpleStatsData",
query = list(
appId = id,
statsDataId = "0000020201",
sectionHeaderFlg = 2
)
)df_tokyo_pop <- read_csv(content(get_estat, as = "text"), skip = 1) %>%
filter(str_detect(地域, "東京都"),
調査年 == "2015年度", cat01_code == "A1101") %>%
select(area = 地域, year = 調査年, population = value) %>%
separate(area, into = c("prefecture", "city"), sep = " ") %>%
mutate(
year = as.integer(str_remove_all(year, "年度"))
) %>%
filter(city != "特別区部") %>%
filter(str_detect(city, "区")) %>%
select(year, prefecture, city, population)
rmarkdown::paged_table(df_tokyo_pop)city, population) だけに絞るdf_tokyo_pop <- df_tokyo_pop %>%
select(city, population)e-Stat から「手動」もしくは「自動」で入手した東京23区の「人口データ」と「1.1 東京23区の地図データを取得」で入手した「地図データ」をマージするtokyo_pop.csvもしくは df_tokyo_pop) と「地図データ」(df_tokyo_sf)をマージするtokyo_pop.csv) と「地図データ」(df_tokyo_sf)をマージするdata という名称のフォルダを作るdataフォルダの中に tokyo_pop.csv ファイルを入れてデータを読み取り df_tokyo_pop と名前をつけるdf_tokyo_pop <- read_csv("data/tokyo_pop.csv")df_tokyo_pop) の表示head(df_tokyo_pop)1.1 東京23区の地図データを取得」でダウンロードした東京都の地図データ (df_tokyo_sf) を表示させるhead(df_tokyo_sf)city) を手がかりに東京の地図データ (df_tokyo_sf) と東京の人口データ (df_tokyo_pop) をマージして、merge_tokyo というデータフレーム名をつけるmerge_tokyo <- df_tokyo_sf %>%
left_join(df_tokyo_pop, by = "city") %>%
st_as_sf()merge_tokyo %>%
head() %>%
rmarkdown::paged_table()merge_tokyo <- merge_tokyo %>%
select(city, geometry, population)merge_tokyo %>%
head() %>%
rmarkdown::paged_table()geometrypopulationcitymerge_tokyo) を使って、人口の多い区を濃い緑色でマップ表示するmap_pop_tokyo <- merge_tokyo %>%
ggplot() +
geom_sf(aes(fill = population)) +
scale_fill_distiller(name = "人口",
palette = "Greens", direction = 1) +
theme_map(base_family = "HiraginoSans-W3") +
theme(legend.position = c(.1, -.1),
legend.direction = "horizontal",
legend.title = element_text(size = 15),
legend.text = element_text(size = 15),
legend.key.size = unit(1, "cm"),
legend.key.width = unit(3,"cm")) +
coord_sf(datum = NA)
map_pop_tokyo・さらに23区名をマップ上に表示させる
map_pop_tokyo_text <- merge_tokyo %>%
mutate(
text_x = map_dbl(geometry, ~st_centroid(.x)[[1]]),
text_y = map_dbl(geometry, ~st_centroid(.x)[[2]])
) %>%
ggplot() +
geom_sf(aes(fill = population)) +
geom_label(aes(x = text_x, y = text_y, label = city),
size = 1.7, family = "HiraginoSans-W3") +
scale_fill_distiller(name = "人口",
palette = "Greens", direction = 1) +
theme_map(base_family = "HiraginoSans-W3") +
theme(legend.position = c(.8, .05),
legend.title = element_text(size = 10),
legend.text = element_text(size = 5),
legend.key.size = unit(0.5, "cm"),
legend.key.width = unit(1,"cm")) +
coord_sf(datum = NA)
map_pop_tokyo_textfig に保存したければ、保存する前に予め Rプロジェクトフォルダに fig という名称のフォルダを作り、次のコマンドを入力するggsave("fig/map_pop_tokyo_text.png", map_pop_tokyo_text, width = 13, height = 13)jpndistrict パッケージをロードするremotes::install_github("uribo/jpndistrict")→ 都道府県別の地図データを抽出する → df_map_jpn という名前を付ける
df_jpn_map <- 1:47 %>%
map(~ jpn_pref(pref_code = ., district = FALSE)) %>%
reduce(rbind) %>%
st_simplify(dTolerance = 0.01)
df_jpn_map の中身を確認し、宮城県の pref_code を確認するDT::datatable(df_jpn_map)pref_code は 4 番df_miyagi_sf <- jpn_pref(pref_code = 4) df_miyagi_sf %>%
ggplot() +
geom_sf() +
theme_minimal()head(df_miyagi_sf)geometry)pupulation)city)city の中には次の 3 種類の行政区が含まれていることがわかる例:仙台市 泉区 → 泉区)例:遠田郡 涌谷町 → 涌谷町)shi と ku_cho) を作成するshi の中に、「泉区」は ku_cho の中に入れるshi の中に、「涌谷町」は ku_cho の中に入れるdf_miyagi_sf <- jpn_pref(pref_code = 4) %>%
separate(city,
into = c("shi", # city の中の前半部分を shi に入れる
"ku_cho"), # city の中の後半部分を shi に入れる
sep = " ") # 前半と後半に区切りはクオーテーション
# クオーテーションの間に「半角のスペース」を入れる
df_miyagi_sfcity を新たに作り、その中に宮城県に関する次の 3 種類の行政区が全て含まれるようにしたいif_else 関数を使うku_cho の値が NA なら city の中に変数 shi の値を入れるcity の中に変数 ku_cho の値を入れると指定df_miyagi_sf <- df_miyagi_sf %>%
mutate(
city = if_else(is.na(ku_cho), shi, ku_cho)
) %>%
select(pref_code:city_code, city, geometry) # 残したい変数を指定
# pref_code:city_code → pref_code から city までの変数を残す
# city と geomerty も残す df_miyagi_sfe-Stat)にアクセスして手動でデータをダウンロードe-Stat)にアクセスして「アプリケーションID」を取得し自動でデータをダウンロードどちらかの方法でデータを取得する
1 の「手動」で人口データを入手する場合には「1.2.1 e-Stat からダウンロード(手動)」を参考にする
ここでは 2 の方法でデータをダウンロードしてみる
e-Stat からダウンロード(手動)1.2.1 e-Stat からダウンロード(手動)」を参考にして csvファイルを作成して下さいe-Stat からダウンロード(自動)e-stat の API を利用して人口を取得するAPI やアプリケーション ID を使ったデータの取得に関してはこちらを参照id <- "取得したアプリケーションID"get_estat <- GET(
url = "http://api.e-stat.go.jp", path = "rest/2.1/app/getSimpleStatsData",
query = list(
appId = id,
statsDataId = "0000020201",
sectionHeaderFlg = 2
)
)csvファイルを読み取る際、一行目をスキップする (skip = 1)調査年 == "2015年度")filter(str_detect(地域, "宮城県"))area を prefecture と city の二つの変数に分けて入れるdf_miyagi_pop) を確認するdf_miyagi_pop <- read_csv(content(get_estat, as = "text"), skip = 1) %>%
filter(str_detect(地域, "宮城県"),
調査年 == "2015年度",
cat01_code == "A1101") %>%
select(area = 地域,
year = 調査年,
population = value) %>%
mutate(
area = str_remove_all(area, " 仙台市")
) %>%
separate(area, into = c("prefecture", "city"), sep = " ") %>%
mutate(
year = as.integer(str_remove_all(year, "年度"))
) %>%
filter(!is.na(city)) %>% # city の欠損値を除外する
select(year, prefecture, city, population) # 分析に必要な変数だけを残すdf_miyagi_pop) の中身を確認df_miyagi_popdf_miyagi_pop) と「2.1 宮城県の地図データを取得」で前処理した宮城県の地図データ (df_miyagi_sf) を city という変数を手がかりにマージするmerge_miyagi <- df_miyagi_sf %>%
left_join(df_miyagi_pop, by = "city") %>%
st_as_sf()names(merge_miyagi)[1] "pref_code" "prefecture.x" "city_code" "city" "geometry"
[6] "year" "prefecture.y" "population"
geometry)pupulation)city)df_miyagi_sf からこれら 3 つの変数だけを抜き出すmerge_miyagi <- merge_miyagi %>%
select(geometry, population, city)DT::datatable(merge_miyagi)map_pop_miyagi <- merge_miyagi %>%
mutate(
text_x = map_dbl(geometry, ~ st_centroid(.x)[[1]]),
text_y = map_dbl(geometry, ~ st_centroid(.x)[[2]])
) %>%
ggplot() +
geom_sf(aes(fill = population)) +
geom_label_repel(aes(x = text_x, y = text_y, label = city),
size = 5, family = "HiraginoSans-W3",
min.segment.length = 0) +
scale_fill_distiller(name = "人口",
palette = "Blues", direction = 1) +
theme_map(base_family = "HiraginoSans-W3") +
theme(legend.position = c(.65, .1),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15),
legend.key.size = unit(1.5, "cm"),
legend.key.width = unit(2,"cm")) +
coord_sf(datum = NA)
map_pop_miyagifig に保存するfig に保存したければ、保存する前に予め Rプロジェクトフォルダに fig という名称のフォルダを作り、次のコマンドを入力するggsave("fig/map_pop_miyagi.png", map_pop_miyagi,
width = 18, height = 15)Question 1: 「1. 東京23区の人口別地図を描く」や「2. 宮城県の人口別地図を描く」の手法を参考にして、あなたが興味ある都道府県を選び、人口規模別のマップを描きなさい
Question 2:得られた結果からどのようなことが言えるか説明しなさい