R ggplot2 上級編:レイヤーの重ね合わせとファセッティング手法
前回のレッスンでは、ggplot2の「3部作」
ggplot() + aes() + geom_xxx()について学び、5つの基本的なプロットを作成する方法を習得しました。今回のレッスンでは、ggplot2の応用編に進み、「レイヤーの積み重ね」と「フェイシングシステム」を習得して、どんなに複雑なプロットでも作成できるようにします。こここそが、ggplot2の真価が発揮される場面です。
このレッスンを修了すると、多層合成プロット、自動顔セグメンテーション、統計情報のオーバーレイ、座標変換、および注釈を作成できるようになります。ggplot2で可能な機能の90%が、このレッスンで網羅されています。
1. 学習内容
- ggplot2の7層構文に関する解説
- レイヤーオーバーレイ(複数のジオメトリ+統計情報)
- facet_wrap() / facet_grid() ファセット表示
- stat_summary() 統計レイヤー
- 座標変換(coord_flip / coord_polar / coord_fixed)
- 注釈
- 複素組み合わせグラフの実用的な応用
2. 多次元分析の物語
(1) 課題:4つの都市、4つの地区、4つの製品について、どのようにビジュアルを作成すればよいでしょうか?
ボブは、4つの都市 × 4四半期 × 4つの製品に関する売上データを提示したいと考えています。この3次元情報を1つのグラフで表現することは可能でしょうか?
(2) ggplot2 による解決策
# Use facet_wrap() to split "Products" into 4 small plots
ggplot(sales, aes(x = quarter, y = sales, color = city, group = city)) +
geom_line(linewidth = 1) +
geom_point(size = 3) +
facet_wrap(~ product) + # By Product Category
labs(title = "4 City × 4 Products Sales Trends")
# A Single Painting 4 Post a picture,Automatic Page Break!
1行のコード facet_wrap() で、1枚の画像を4枚に分割。これこそがトリミングの力です。
3. ggplot2の7層構文の解説
(1) 7層構造
graph TB
A[ggplot Plot] --> B[1. Data layer<br/>ggplot data]
A --> C[2. Aesthetic Mapping layer<br/>aes]
A --> D[3. Geometric Objects layer<br/>geom_xxx]
A --> E[4. Statistical Transformations layer<br/>stat_xxx]
A --> F[5. Coordinate System layer<br/>coord_xxx]
A --> G[6. Sub-section layer<br/>facet_xxx]
A --> H[7. Topic layer<br/>theme_xxx]
style A fill:#fff3cd
style B fill:#cce5ff
style C fill:#d4edda
style D fill:#f8d7da
style E fill:#e1d4ff
style F fill:#ffe1e1
style G fill:#e1ffe1
style H fill:#ffe1d4
(2) レイヤーオーバーレイの例
ggplot(df, aes(x, y)) + # Data + Aesthetics
geom_point() + # Geometric Layer 1:Scatter points
geom_smooth() + # Geometric Layer 2:Trendline
stat_summary() + # Statistical Layer
scale_y_log10() + # Coordinate Transformation
facet_wrap(~ group) + # Sub-section
theme_minimal() # Topic
+ ごとにレイヤーを追加し、下から上の順に重ねてください。
4. facet_wrap() / facet_grid() によるファセット表示
(1) ファセットとは何ですか?
ファセット = 特定の変数に基づいてデータを複数のサブプロットに分割すること:
# Cone of Inadmissibility:1 Post a picture
ggplot(sales, aes(x, y)) + geom_point()
# After splitting:4 Zhang Xiaotu
ggplot(sales, aes(x, y)) + geom_point() + facet_wrap(~ category)
(2) facet_wrap() 1次元ファセット
# Split by city(4 subplots)
ggplot(sales_long, aes(x = quarter, y = sales, color = city, group = city)) +
geom_line() +
facet_wrap(~ city) +
labs(title = "Quarterly Sales by City")
# Control the Layout of Sub-Faces:nrow / ncol
facet_wrap(~ city, nrow = 2) # 2 row
facet_wrap(~ city, ncol = 4) # 4 col
(3) facet_grid() 2次元ファセット
# Split by city(row) and product(col) Two-Dimensional Section
facet_grid(rows = vars(city), cols = vars(product))
# Abbreviation
facet_grid(city ~ product)
# Formula Syntax(Old Version)
facet_grid(. ~ category) # Press only category Split Plane
facet_grid(category ~ .) # Press only category Row-Column Plane
(4) 側面別の比較
| 構文 | 使い方 |
|---|---|
facet_wrap(~ var) |
一次元ファセッティング(自動改行) |
facet_grid(var ~ .) |
1次元(行) |
facet_grid(. ~ var) |
1次元(列) |
facet_grid(row ~ col) |
2次元(行×列) |
(5) ファセット拡張
# Free Zoom(Independent coordinates for each subgraph)
facet_wrap(~ city, scales = "free") # Freedom x/y
facet_wrap(~ city, scales = "free_x") # Freedom Alone x
facet_wrap(~ city, scales = "free_y") # Freedom Alone y
# Add a tag
facet_wrap(~ city, labeller = label_both) # Display"city: Beijing"
# Control the number of subgraphs per row
facet_wrap(~ city, nrow = 2)
5. stat_summary() 統計レイヤー
(1) 自動統計
# Automatically Add Mean Points + Error bar
ggplot(df, aes(x = group, y = value)) +
geom_boxplot() +
stat_summary(fun = mean, geom = "point", color = "red", size = 3)
(2) 一般的な統計関数
| 機能 | 目的 |
|---|---|
mean |
平均 |
median |
中央値 |
sd |
標準偏差 |
sum |
合計 |
function(x) mean(x) + sd(x) |
カスタム |
(3) 実践的な応用:平均値と誤差棒
ggplot(df, aes(x = group, y = value, color = group)) +
geom_point(alpha = 0.3) + # Raw Data
stat_summary(fun = mean, geom = "point", size = 4, color = "red") +
stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.2)
6. geom_smooth() トレンドライン
(1) 基本的な使い方
# Auto-add LOESS Trendline
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth()
# Linear Regression
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm")
# Close Confidence Interval
geom_smooth(method = "lm", se = FALSE)
(2) 実践的な応用
# Multiple lines by component
ggplot(sales_long, aes(x = quarter, y = sales, color = city, group = city)) +
geom_point() +
geom_line() +
geom_smooth(method = "lm", se = FALSE, linewidth = 0.5)
7. 座標変換
(1) coord_flip() 反転
# Horizontal Bar Chart
ggplot(df, aes(x = city, y = sales)) +
geom_col() +
coord_flip() # x/y Swap
(2) coord_polar() 極座標
# Pie Chart
ggplot(df, aes(x = 1, y = sales, fill = city)) +
geom_col() +
coord_polar(theta = "y")
# Rose Illustration
ggplot(df, aes(x = city, y = sales, fill = city)) +
geom_col() +
coord_polar()
(3) coord_fixed()(比例的に拡大・縮小)
# Scatter Plot X/Y In the same proportion
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
coord_fixed(ratio = 1) # 1:1 Ratio
(4) 座標軸の変換
# log Transformation
ggplot(df, aes(x, y)) + geom_point() + scale_y_log10()
# Square Root Transformation
ggplot(df, aes(x, y)) + geom_point() + scale_y_sqrt()
8. コメントとテキスト
(1) geom_text() / geom_label()
# Add labels next to the data points
ggplot(df, aes(x, y)) +
geom_point() +
geom_text(aes(label = name), vjust = -0.5)
# Add a circular label
ggplot(df, aes(x, y)) +
geom_point() +
geom_label(aes(label = name))
(2) annotate() による手動アノテーション
# Mark Key Points
ggplot(df, aes(x, y)) +
geom_point() +
annotate("text", x = 5, y = 8, label = "Key Points", color = "red") +
annotate("rect", xmin = 4, xmax = 6, ymin = 7, ymax = 9,
alpha = 0.2, fill = "yellow")
(3) 矢印
library(ggrepel)
# "Auto-Skip" tag
ggplot(df, aes(x, y, label = name)) +
geom_point() +
geom_text_repel() # Non-overlapping tags
9. 複数の画像を組み合わせる
(1) パッチワークバッグ
# Installation
install.packages("patchwork")
library(patchwork)
# 4 Image Collage 1
(p1 + p2) / (p3 + p4) # 2 row 2 col
# Complex Layout
p1 + p2 + p3 + p4 + plot_layout(ncol = 2, heights = c(2, 1))
# Add a title
(p1 + p2) / (p3 + p4) + plot_annotation(title = "Comprehensive Analysis")
(2) cowplot パッケージ
library(cowplot)
plot_grid(p1, p2, p3, p4, ncol = 2, labels = c("A", "B", "C", "D"))
10. 完全な例:4つの都市 × 4つの製品――多次元分析
以下は、このレッスンで取り上げたすべての高度な機能を組み合わせた完全なワークフローの例です。
▶ サンプル:多次元売上データの包括的な可視化
# ============================================
# 4 City × 4 Products Multidimensional Sales Analysis
# Features:Sub-section + Trendline + Notes + Multi-Image Collage
# ============================================
library(ggplot2)
library(dplyr)
library(tidyr)
library(patchwork)
# 1. Prepare data
sales <- expand_grid(
city = c("Beijing", "Shanghai", "Guangzhou", "Shenzhen"),
quarter = c("Q1", "Q2", "Q3", "Q4"),
product = c("Cell Phone", "Computer", "Tablet", "Headphones")
) |>
mutate(sales = round(runif(64, 500, 3000)))
cat("=== Data Volume:", nrow(sales), "row ===\n")
print(head(sales, 5))
# 2. Plot 1:4 Overall Urban Trends(Basics)
p1 <- ggplot(sales, aes(x = quarter, y = sales, color = city, group = city)) +
geom_line(linewidth = 1) +
geom_point(size = 2) +
labs(title = "4 Overall Sales Trends by City", color = "City") +
theme_minimal() +
theme(legend.position = "bottom")
# 3. Plot 2:By City(facet_wrap)
p2 <- ggplot(sales, aes(x = quarter, y = sales, color = product, group = product)) +
geom_line(linewidth = 1) +
geom_point(size = 2) +
facet_wrap(~ city, nrow = 2) +
labs(title = "Product Sales by City", color = "Products") +
theme_minimal() +
theme(legend.position = "bottom",
axis.text.x = element_text(angle = 45, hjust = 1))
# 4. Plot 3:By City(By Product Stack)
p3 <- ggplot(sales, aes(x = quarter, y = sales, fill = product)) +
geom_col(position = "stack") +
facet_wrap(~ city, nrow = 2) +
labs(title = "Product Bundle Sales by City", fill = "Products") +
scale_fill_brewer(palette = "Set2") +
theme_minimal() +
theme(legend.position = "bottom")
# 5. Plot 4:Trendline + Original Point
p4 <- ggplot(sales, aes(x = quarter, y = sales, color = city, group = city)) +
geom_point(alpha = 0.3) +
geom_smooth(method = "lm", se = TRUE) +
labs(title = "Linear Trendline + Confidence Interval") +
theme_minimal() +
theme(legend.position = "bottom")
# 6. Plot 5:Box-and-Whisker Plots
p5 <- ggplot(sales, aes(x = product, y = sales, fill = product)) +
geom_boxplot() +
labs(title = "Sales Breakdown by Product") +
theme_minimal() +
theme(legend.position = "none",
axis.text.x = element_text(angle = 45, hjust = 1))
# 7. Plot 6:Heat Map(geom_tile)
sales_summary <- sales |>
group_by(city, product) |>
summarise(total = sum(sales), .groups = "drop")
p6 <- ggplot(sales_summary, aes(x = city, y = product, fill = total)) +
geom_tile() +
geom_text(aes(label = total), color = "white") +
labs(title = "City × Products Total Sales Heat Map", fill = "Total Sales") +
scale_fill_gradient(low = "lightblue", high = "darkred") +
theme_minimal()
# 8. Multi-Image Collage(patchwork)
combined <- (p1 + p2) / (p3 + p4) / (p5 + p6) +
plot_annotation(
title = "4 City × 4 Products Comprehensive Sales Analysis",
subtitle = "Data Simulation | ggplot2 Photo Gallery"
)
print(combined)
# 9. Save as high resolution PNG
ggsave("multi_dimension_analysis.png", combined,
width = 16, height = 18, dpi = 300)
cat("\n=== The composite image has been saved:multi_dimension_analysis.png ===\n")
期待される出力:6つの部分画像から構成される大きな画像(「パッチワーク」法を用いて3×2のグリッドに配置されたもの)。
❓ よくある質問
facet_wrap と facet_grid の違いは何ですか?facet_wrap(~ var) は1次元ファセット(自動改行)、facet_grid(rows ~ cols) は2次元ファセット(行と列が固定)です。geom_smooth のデフォルト設定はどのようなものですか?method = "lm" を追加してください。theme(strip.background = element_blank())(背景の削除)+ theme(strip.text = element_text(color = "red"))(文字色の変更)。p1 + p2、上下配置には p1 / p2、2×2配置には (p1 + p2) / (p3 + p4) を使用します。複雑なレイアウトには plot_layout(ncol = 2) を使用してください。ggrepel を使って geom_text_repel() / geom_label_repel() を囲めば、データポイントが自動的に回避されます。coord_flip 90度回転させます(横軸のグラフ)、coord_polar 極座標に変換します(円グラフ/ローズチャート)。📖 まとめ
- ggplot2の7層構文:データ/美学/幾何/統計/座標/ファセット/テーマ
- 重ね着には
+を使用し、下から上へと重ねていく - 向き:
facet_wrap(~ var)1次元 /facet_grid(rows ~ cols)2次元 geom_smooth()トレンドラインの自動追加(LOESS/lm)stat_summary()平均値や誤差棒などの統計レイヤーを追加する- 座標変換:
coord_flip反転 /coord_polar極座標 /scale_y_log10対数変換 - 備考:
geom_textデータラベル /annotate手動アノテーション /ggrepel自動回避 - 複数画像セット:
patchworkパッケージ(推奨)/cowplotパッケージ - ggplot2 上級者向け = レイヤーの組み合わせの技法—単純なレイヤーから複雑なプロットを構築する
📝 練習問題
-
基本演習:データフレーム(30行、4列:x/y/group/category)を作成し、
facet_wrap(~ group)を使用して散布図を描画し、スライシングの効果を確認します。その後、facet_grid(group ~ category)を使用して2次元スライス図を描画します。 -
基本演習:
mtcarsを用いて、wt対mpgの散布図を作成し、geom_smooth(method = "lm")に対する傾向線を追加し、geom_smooth(method = "lm", formula = y ~ poly(x, 2), color = "red")に対する2次曲線を描き、2つの近似結果を比較してください。 -
基本演習:棒グラフ(5つのカテゴリ)を描き、
coord_flip()を使って水平方向に回転させ、次にcoord_polar()を使って円グラフに変換し、その違いを比較してください。 -
応用演習:3次元データ(x/y/グループ)を作成し、ggplot2 を使用して 3 つの横断プロット(
facet_wrap)を描画し、最後にpatchworkを使用して、それらを要約タイトル付きの 1×3 の水平組み合わせプロットに統合します。 -
課題:総合課題—「出版物レベルの品質」を備えた合成グラフを1つ作成する:①
mtcarsの4次元データ(重量/燃費/気筒数/馬力)を使用する ②facet_wrap(~ cyl)を使用して気筒数ごとにセグメント分けする ③ LOESS トレンドラインを追加する ④ggrepelを使用して上位 3 車種と下位 3 車種を強調表示する ⑤patchworkを使用して参考用の箱ひげ図を追加する ⑥ 高解像度の PNG 形式で保存する。



