0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

e-statデータから箱ひげ図の作成

Last updated at Posted at 2025-02-21

目的:家計調査データの可視化
使用データ:<品目分類>1世帯当たり年間の品目別支出金額 都市階級・地方・都道府県庁所在市別(総世帯)
https://www.e-stat.go.jp/stat-search/files?page=1&layout=datalist&toukei=00200561&tstat=000000330001&cycle=7&year=20240&month=0&tclass1=000000330001&tclass2=000000330019&tclass3=000000330020&result_back=1&cycle_facet=tclass1%3Atclass2&tclass4val=0
ファイル名:s11.xls
実行環境:RStudio
前処理:総(りんご~電気冷蔵庫)シート以外削除、縦軸は都道府県庁所在地のみ、横軸は品目のみにしました

必要なパッケージのインストール

install.packages(c("tidyverse", "showtext", "readr"))

CSVデータの読み込み

library(tidyverse)
file_path <- "C:\ディレクトリ名\ファイル名.csv" #setwd()で作業ディレクトリを指定する
data <- read_csv(file_path, locale = locale(encoding = "SHIFT-JIS"))
str(data)

データの整形

data <- data %>%
    mutate(across(where(is.character), ~ as.numeric(gsub(",", "", .)), .names = "converted_{col}"))

データをロングフォーマットに変換

data_long <- data %>%
    pivot_longer(cols = -location, names_to = "item", values_to = "value") %>%
    drop_na()
head(data_long)

箱ひげ図を作成

library(ggplot2)
library(showtext)

# 日本語フォントの設定

font_add("meiryo", "C:/Windows/Fonts/meiryo.ttc")
showtext_auto()

# 今回はこの8市をハイライト

highlight_cities <- c("静岡市", "名古屋市", "津市", 
                      "岐阜市", "大津市", "横浜市", "甲府市", "浜松市")

# PDFの保存先(PCの実際のユーザー名に変更する)
~
pdf_path <- "C:/Users/保存先のディレクトリ/ファイル名.pdf"
pdf(pdf_path, width = 12, height = 8)  # A4サイズのPDF

# 品目ごとの箱ひげ図を作成
~~~r
for (item_name in unique(data_long$item)) {
    p <- ggplot(data_long %>% filter(item == item_name), aes(x = "", y = value)) +
        geom_boxplot(fill = "lightblue") +
        geom_point(data = data_long %>% filter(location %in% highlight_cities, item == item_name),aes(x = "", y = value, color = location), size = 3) +
        stat_summary(fun = mean, geom = "point", shape = 4, size = 4, color = "black") +  # 平均値を✖で表示
        ggtitle(item_name) +
        labs(y = "年間支出額", x = "") +
        theme_minimal() +
        theme(
            text = element_text(family = "meiryo"),  # 日本語フォント適用
            plot.title = element_text(hjust = 0.5, size = 10)
        ) +
        scale_color_manual(values = c("red", "blue", "green", "purple", "orange", "pink", "brown","yellow"))

    print(p)
}

# PDFを閉じる
dev.off()

ハンバーグ.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?