政府統計から都道府県の人口データを取得して棒グラフ表示

はじめに 本記事では、Rを使って政府統計(e-Stat)からAPIを使って都道府県の人口データを取得して棒グラフ表示する。 使用する統計表 令和2年国勢調査の「男女別人口-全国,都道府県,市区町村(2000年(平成12年)市区町村含む)」 前準備 API機能を使うには、e-Statでのユーザ登録が必要である。 以下のサイトでユーザ登録を行う。メールアドレスが必要。それ以外に名前や住所などは必要ない。 https://www.e-stat.go.jp/api/ 登録したらログイン後のマイページから「API機能(アプリケーションID発行)」に進んでアプリケーションIDを発行しよう。 名称、URLを適当に(testなどでも可)入力して「発行」を押せば下のappIdに数字とa〜fの組み合わせが表示される。 これがアプリケーションID(appId)になるのでコピーする。 このappIdは発行した人だけが使うものなので他の人には教えないように。 Rプログラム options(crayon.enabled = FALSE) # 色 library(tidyverse) ── Attaching core tidyverse packages ──────────────────────────────────────────────────────────── tidyverse 2.0.0 ── ✔ dplyr 1.1.4 ✔ readr 2.1.5 ✔ forcats 1.0.0 ✔ stringr 1.5.1 ✔ ggplot2 3.5.2 ✔ tibble 3.2.1 ✔ lubridate 1.9.4 ✔ tidyr 1.3.1 ✔ purrr 1.0.4 ── Conflicts ────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ── ✖ dplyr::filter() masks stats::filter() ✖ dplyr::lag() masks stats::lag() ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors apikey = "9a95xxxxxxxxxxxxxxxxxxxxxxxxxxxxx1b24" # 前準備でコピーした自分のappId url <- paste0("http://api.e-stat.go.jp/rest/3.0/app/getSimpleStatsData?appId=", apikey, "&lang=J&statsDataId=0003445078&metaGetFlg=N&cntGetFlg=N&explanationGetFlg=N&annotationGetFlg=N&sectionHeaderFlg=1&replaceSpChars=0") jinkou <- read_csv(url, skip = 27) ── Column specification ──────────────────────────────────────────────────────────────────────────────────────────── Delimiter: "," chr (7): tab_code, 表章事項, 男女, area_code, 全国,都道府県,市区町村(2000年市区町村含む), 時間軸(年次), unit dbl (3): cat01_code, time_code, value ℹ Use `spec()` to retrieve the full column specification for this data. ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message. Warning message: One or more parsing issues, call `problems()` on your data frame for details, e.g.: dat <- vroom(...) problems(dat) 「全国,都道府県,市区町村(2000年市区町村含む)」というカラム名があるので注意。 今回は都道府県のみ抽出するのでrenameでカラム名を都道府県に変更する。 ...

June 1, 2025