404 Not Found

404 Not Found


nginx

R ggplot2 上級編:レイヤーの重ね合わせとファセッティング手法

前回のレッスンでは、ggplot2の「3部作」ggplot() + aes() + geom_xxx()について学び、5つの基本的なプロットを作成する方法を習得しました。今回のレッスンでは、ggplot2の応用編に進み、「レイヤーの積み重ね」と「フェイシングシステム」を習得して、どんなに複雑なプロットでも作成できるようにします。こここそが、ggplot2の真価が発揮される場面です。

このレッスンを修了すると、多層合成プロット、自動顔セグメンテーション、統計情報のオーバーレイ、座標変換、および注釈を作成できるようになります。ggplot2で可能な機能の90%が、このレッスンで網羅されています。

1. 学習内容



2. 多次元分析の物語

(1) 課題:4つの都市、4つの地区、4つの製品について、どのようにビジュアルを作成すればよいでしょうか?

ボブは、4つの都市 × 4四半期 × 4つの製品に関する売上データを提示したいと考えています。この3次元情報を1つのグラフで表現することは可能でしょうか?

(2) ggplot2 による解決策

R
# 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層構造

100%
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) レイヤーオーバーレイの例

R
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) ファセットとは何ですか?

ファセット = 特定の変数に基づいてデータを複数のサブプロットに分割すること

R
# 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次元ファセット

R
# 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")
R
# 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次元ファセット

R
# 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) ファセット拡張

R
# 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) 自動統計

R
# 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) 実践的な応用:平均値と誤差棒

R
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) 基本的な使い方

R
# 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) 実践的な応用

R
# 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() 反転

R
# Horizontal Bar Chart
ggplot(df, aes(x = city, y = sales)) +
  geom_col() +
  coord_flip()  # x/y Swap

(2) coord_polar() 極座標

R
# 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()(比例的に拡大・縮小)

R
# Scatter Plot X/Y In the same proportion
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  coord_fixed(ratio = 1)  # 1:1 Ratio

(4) 座標軸の変換

R
# 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()

R
# 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() による手動アノテーション

R
# 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) 矢印

R
library(ggrepel)

# "Auto-Skip" tag
ggplot(df, aes(x, y, label = name)) +
  geom_point() +
  geom_text_repel()  # Non-overlapping tags


9. 複数の画像を組み合わせる

(1) パッチワークバッグ

R
# 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 パッケージ

R
library(cowplot)
plot_grid(p1, p2, p3, p4, ncol = 2, labels = c("A", "B", "C", "D"))


10. 完全な例:4つの都市 × 4つの製品――多次元分析

以下は、このレッスンで取り上げたすべての高度な機能を組み合わせた完全なワークフローの例です。

▶ サンプル:多次元売上データの包括的な可視化

R
# ============================================
# 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のグリッドに配置されたもの)。


❓ よくある質問

Q facet_wrapfacet_grid の違いは何ですか?
A facet_wrap(~ var) は1次元ファセット(自動改行)、facet_grid(rows ~ cols) は2次元ファセット(行と列が固定)です。
Q geom_smooth のデフォルト設定はどのようなものですか?
A デフォルトは LOESS 平滑化(n < 1000)または GAM(n ≥ 1000)です。線形回帰を使用するには、method = "lm" を追加してください。
Q ページラベルの背景を削除するにはどうすればよいですか?
A theme(strip.background = element_blank())(背景の削除)+ theme(strip.text = element_text(color = "red"))(文字色の変更)。
Q 「パッチワーク」はどのように使えばいいですか?
A 並列配置には p1 + p2、上下配置には p1 / p2、2×2配置には (p1 + p2) / (p3 + p4) を使用します。複雑なレイアウトには plot_layout(ncol = 2) を使用してください。
Q テキストラベルが重ならないように追加するにはどうすればよいですか?
A ggrepel を使って geom_text_repel() / geom_label_repel() を囲めば、データポイントが自動的に回避されます。
Q coord_polar と coord_flip の違いは何ですか?
A coord_flip 90度回転させます(横軸のグラフ)、coord_polar 極座標に変換します(円グラフ/ローズチャート)。

📖 まとめ


📝 練習問題

  1. 基本演習:データフレーム(30行、4列:x/y/group/category)を作成し、facet_wrap(~ group) を使用して散布図を描画し、スライシングの効果を確認します。その後、facet_grid(group ~ category) を使用して2次元スライス図を描画します。

  2. 基本演習mtcars を用いて、wtmpg の散布図を作成し、geom_smooth(method = "lm") に対する傾向線を追加し、geom_smooth(method = "lm", formula = y ~ poly(x, 2), color = "red") に対する2次曲線を描き、2つの近似結果を比較してください。

  3. 基本演習:棒グラフ(5つのカテゴリ)を描き、coord_flip() を使って水平方向に回転させ、次に coord_polar() を使って円グラフに変換し、その違いを比較してください。

  4. 応用演習:3次元データ(x/y/グループ)を作成し、ggplot2 を使用して 3 つの横断プロット(facet_wrap)を描画し、最後に patchwork を使用して、それらを要約タイトル付きの 1×3 の水平組み合わせプロットに統合します。

  5. 課題:総合課題—「出版物レベルの品質」を備えた合成グラフを1つ作成する:① mtcars の4次元データ(重量/燃費/気筒数/馬力)を使用する ② facet_wrap(~ cyl) を使用して気筒数ごとにセグメント分けする ③ LOESS トレンドラインを追加する ④ ggrepel を使用して上位 3 車種と下位 3 車種を強調表示する ⑤ patchwork を使用して参考用の箱ひげ図を追加する ⑥ 高解像度の PNG 形式で保存する。

Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%