404 Not Found

404 Not Found


nginx

R ggplot2 入門:グラフィックスの文法完全ガイド

前回のレッスンでは、Rでの基本的なプロット方法について解説しました。これは速いですが、見栄えは良くありません。今回のレッスンでは、Rの真の「秘密兵器」であるggplot2について詳しく見ていきます。ハドリー・ウィッカムによって設計されたこのライブラリは、「グラフィックスの文法(Grammar of Graphics)」と呼ばれる構文を採用しており、プロット作成を「ブロックを組み立てる」ように簡単に行えるほか、デフォルトで出版物レベルの品質を持つビジュアルを生成し、Rを用いた学術論文の90%で使用されています。

このレッスンを修了すると、ggplot2 を使って 5 つの主要なグラフの種類 を作成できるようになり、「レイヤリング」という基本概念を理解できるようになります。

1. 学習内容



2. データ可視化の物語

(1) 課題:Rの基本インターフェースはあまりにも見苦しい

ボブは、基本的なRを使って、4つの都市における売上動向を示すグラフを作成しました:

R
plot(1:4, sales, type = "b")

マネージャーはそれをちらりと見て、「この画像をレポートに含めてもいいですか?」と尋ねた。

(2) ggplot2 による解決策

R
library(ggplot2)

ggplot(sales_df, aes(x = quarter, y = sales, color = city, group = city)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  labs(title = "Q1-Q4 Sales Trends", x = "Quarter", y = "Sales") +
  theme_minimal()

たった4行のコードで、デフォルトでも出版物レベルの品質の図を作成。これこそがggplot2の真骨頂です。



3. 「グラフィックスの文法」の核心概念

(1) 「グラフィックスの文法」とは何か?

100%
graph TB
    A[ggplot2 Charts] --> B[Data Data<br/>data]
    A --> C[Aesthetic Mapping Aesthetics<br/>aes]
    A --> D[Geometric Objects Geometries<br/>geom_xxx]
    A --> E[Statistical Transformations Statistics<br/>stat_xxx]
    A --> F[Coordinate System Coordinate<br/>coord_xxx]
    A --> G[Sub-section Facet<br/>facet_xxx]
    A --> H[Topic Theme<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

一言で言えば:ggplot2はプロットを7つのレイヤーに分解しており、各レイヤーは独立しており、置き換え可能です。

(2) ggplot2の3つの柱

機能 目的
ggplot() 初期化(指定データ) ggplot(df)
aes() 美的マッピング(変数 → 視覚表現) aes(x, y, color)
geom_xxx() 幾何学的オブジェクト(レイヤー) geom_point()

最小限の例

R
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point()


4. 最初の ggplot2 プロット

(1) 5段階のデッサン手順

R
library(ggplot2)

# 1. Prepare data
df <- data.frame(
  x = 1:10,
  y = (1:10) ^ 2
)

# 2. Initialization(Data)
p <- ggplot(df, aes(x = x, y = y))

# 3. Add a Layer
p <- p + geom_point()

# 4. Add a tag
p <- p + labs(title = "Quadratic Curve", x = "X", y = "Y")

# 5. Add a topic
p <- p + theme_minimal()

# 6. Print
print(p)

あるいは、+ を使って、これらをまとめて実行することもできます:

R
ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  labs(title = "Quadratic Curve", x = "X", y = "Y") +
  theme_minimal()
💡 ヒント: ggplot2では、+ を使ってレイヤーを連結します。これは、|> を使ってデータ操作を連結するのと同様です。

(2) ファイルへの出力

R
# Save as PNG
ggsave("myplot.png", width = 8, height = 6, dpi = 300)

# Save as PDF(For a thesis)
ggsave("myplot.pdf", width = 8, height = 6)

# Custom Size
ggsave("myplot.png", width = 10, height = 8, units = "cm", dpi = 300)


5. 美的マッピング aes()

(1) 一般的なマッピング

マッピング 関数
x, y X / Y座標 aes(x = age, y = height)
color / colour 色(外側) aes(color = gender)
fill 塗りつぶし色(棒グラフ/面塗り) aes(fill = region)
size 文字サイズ aes(size = amount)
shape ドット形状 aes(shape = category)
alpha 透明性 aes(alpha = weight)
linetype リニア aes(linetype = type)

(2) 実用例:3次元マッピング

R
# Color + Size + Shape 3 dimensions
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl), size = hp)) +
  geom_point(alpha = 0.7) +
  labs(title = "Vehicle Weight vs Fuel Consumption", color = "Number of cylinders", size = "Horsepower")

(3) ⚠️ aes() の内部と外部

R
# aes() Inside:Map to a variable(Each dot is a different color)
ggplot(df, aes(x, y, color = group)) + geom_point()
# → Different group Display different colors

# aes() Outside:Fixed value(All dots are the same color)
ggplot(df, aes(x, y)) + geom_point(color = "red")
# → All the dots are red
💡 ヒントaes() 内の color = "red" は、「赤の列」として解釈されます(データに赤の列が含まれている場合)。固定色は aes() の外側に記述する必要があります



6. 5 基本的なジオメトリ

(1) geom_point() 散布図

R
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
  geom_point(size = 3) +
  labs(title = "Vehicle Weight vs Fuel Consumption", x = "Weight", y = "Fuel Consumption")

(2) geom_line() 折れ線グラフ

R
df <- data.frame(
  x = 1:10,
  y = c(2, 4, 3, 5, 4, 6, 5, 7, 6, 8),
  group = "A"
)

ggplot(df, aes(x = x, y = y)) +
  geom_line(color = "blue", linewidth = 1) +
  geom_point(color = "blue", size = 3)

(3) geom_bar() 棒グラフ

R
# Data
df <- data.frame(
  city = c("Beijing", "Shanghai", "Guangzhou", "Shenzhen"),
  sales = c(4800, 7000, 3900, 4500)
)

# Bar Chart
ggplot(df, aes(x = city, y = sales, fill = city)) +
  geom_bar(stat = "identity") +  # identity = Use y values
  labs(title = "Total Sales by City", x = "City", y = "Sales") +
  theme_minimal()
⚠️ 注意geom_bar(stat = "identity") はデータから y 値を使用します。一方、geom_bar() はデフォルトでカウントを行います。

(4) geom_histogram() ヒストグラム

R
# 1000 A random number from a normal distribution
data <- data.frame(x = rnorm(1000, mean = 100, sd = 15))

ggplot(data, aes(x = x)) +
  geom_histogram(bins = 30, fill = "skyblue", color = "white") +
  labs(title = "Normal Distribution", x = "Value", y = "Frequency")

(5) geom_boxplot() 箱ひげ図

R
# 4 Class Test Scores
scores <- data.frame(
  class = rep(c("1Cls", "2Cls", "3Cls", "4Cls"), each = 10),
  score = c(rnorm(10, 80, 8), rnorm(10, 75, 10),
            rnorm(10, 85, 7), rnorm(10, 70, 12))
)

ggplot(scores, aes(x = class, y = score, fill = class)) +
  geom_boxplot() +
  labs(title = "4 Class Grade Distribution", x = "Class", y = "Fractions")


7. タグとトピック

(1) labs() タグ

R
ggplot(df, aes(x, y)) +
  geom_point() +
  labs(
    title = "Main Title",
    subtitle = "Subtitle",
    caption = "Data Sources:xxx",
    x = "X Axis",
    y = "Y Axis",
    color = "Color Mapping",
    fill = "Fill Mapping"
  )

(2) テーマ theme_xxx()

テーマ スタイル
theme_minimal() ミニマリスト (最も一般的)
theme_bw() 白黒
theme_classic() 古典(学術)
theme_void() 空白
theme_light() ライト
theme_dark() ダーク
R
# Comparison 4 Topics
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
(p + theme_minimal())  # Default Recommendation
(p + theme_bw())
(p + theme_classic())
(p + theme_void())

(3) テーマの微調整

R
p + theme(
  plot.title = element_text(size = 16, face = "bold"),
  axis.text = element_text(size = 10),
  legend.position = "bottom"  # Legend Location
)


8. 色とマッピング

(1) 個別の色

R
# 1. Built-in Color Palette
p + scale_color_brewer(palette = "Set1")    # Classic
p + scale_color_brewer(palette = "Dark2")    # Dark
p + scale_color_brewer(palette = "Pastel1")  # Light-colored

# 2. Specify manually
p + scale_color_manual(values = c("red", "blue", "green"))

# 3. rainbow
p + scale_color_manual(values = rainbow(4))

(2) 連続色

R
# Gradient(For continuous variables)
p + scale_color_gradient(low = "blue", high = "red")
p + scale_color_viridis_c()   # viridis(Recommendations)
p + scale_color_distiller(palette = "RdYlBu")


9. 完全な例:4都市における複数画像の販売

以下は、このレッスンで取り上げたすべての概念を結びつけた完全なワークフローの例です。

▶ サンプル:4つの都市、5枚の写真のコレクション

R
# ============================================
# 4 City Sales 5 Image Gallery
# Features:Use ggplot2 to create 5 publication-quality charts
# ============================================

library(ggplot2)
library(dplyr)
library(tidyr)

# 1. Prepare data
sales_wide <- tibble(
  city = c("Beijing", "Shanghai", "Guangzhou", "Shenzhen"),
  Q1 = c(1000, 1500, 800, 1200),
  Q2 = c(1200, 1800, 900, 1400),
  Q3 = c(1100, 1700, 1000, 1300),
  Q4 = c(1500, 2000, 1200, 1600)
)

sales_long <- sales_wide |>
  pivot_longer(cols = -city, names_to = "quarter", values_to = "sales")

cat("=== Sales Data ===\n")
print(sales_long)

# 2. Plot 1:Linear Trend(By City)
p1 <- ggplot(sales_long, aes(x = quarter, y = sales, color = city, group = city)) +
  geom_line(linewidth = 1) +
  geom_point(size = 3) +
  labs(title = "Q1-Q4 Sales Trends", x = "Quarter", y = "Sales", color = "City") +
  scale_color_brewer(palette = "Set1") +
  theme_minimal()

print(p1)

# 3. Plot 2:Total Sales Bar Chart
total_sales <- sales_wide |>
  mutate(total = Q1 + Q2 + Q3 + Q4) |>
  select(city, total)

p2 <- ggplot(total_sales, aes(x = reorder(city, total), y = total, fill = city)) +
  geom_bar(stat = "identity") +
  coord_flip() +  # Sideways
  labs(title = "Total Sales by City", x = "City", y = "Total Sales") +
  theme_minimal() +
  theme(legend.position = "none")

print(p2)

# 4. Plot 3:Pie Chart of Percentage Distributions(geom_bar + coord_polar)
p3 <- ggplot(total_sales, aes(x = "", y = total, fill = city)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar(theta = "y") +  # Polar Coordinates(Pie Chart)
  labs(title = "Share of Sales") +
  theme_void() +
  scale_fill_brewer(palette = "Set2")

print(p3)

# 5. Plot 4:Histogram(All Sales Data)
p4 <- ggplot(sales_long, aes(x = sales, fill = city)) +
  geom_histogram(bins = 10, alpha = 0.7, position = "identity") +
  labs(title = "Sales Distribution", x = "Sales", y = "Frequency") +
  scale_fill_brewer(palette = "Set1") +
  theme_minimal()

print(p4)

# 6. Plot 5:Box-and-Whisker Plot(By City)
p5 <- ggplot(sales_long, aes(x = city, y = sales, fill = city)) +
  geom_boxplot() +
  labs(title = "Sales Distribution by City", x = "City", y = "Sales") +
  theme_minimal() +
  theme(legend.position = "none")

print(p5)

# 7. Save All Images
ggsave("01_trend.png", p1, width = 8, height = 6, dpi = 300)
ggsave("02_total.png", p2, width = 8, height = 6, dpi = 300)
ggsave("03_pie.png", p3, width = 8, height = 6, dpi = 300)
ggsave("04_hist.png", p4, width = 8, height = 6, dpi = 300)
ggsave("05_box.png", p5, width = 8, height = 6, dpi = 300)

cat("\n=== 5 The image has been saved ===\n")
cat("  01_trend.png - Linear Trend\n")
cat("  02_total.png - Bar Chart Comparison\n")
cat("  03_pie.png - Pie Chart of Percentage Distributions\n")
cat("  04_hist.png - Histogram\n")
cat("  05_box.png - Urban Box Lines\n")
▶ 試してみよう

期待される成果物:出版物として十分な品質の図表5点(デフォルトの「theme_minimal」はすでに十分に魅力的です)。


❓ よくある質問

Q geom_bar()geom_col() の違いは何ですか?
A geom_bar(stat = "identity")y の値を使用します。geom_col() はその構文糖衣(より簡潔な表記)です。geom_bar()はデフォルトでカウントされます(yは不要です)。
Q コメントを追加するにはどうすればよいですか?
A geom_text() / geom_label() を使用してください:
R
ggplot(df, aes(x, y)) + geom_point() +
  geom_text(aes(label = name), vjust = -0.5)  # Add labels above the data points
Q 凡例を削除するにはどうすればよいですか?
A theme(legend.position = "none")
Q 高解像度の画像を保存するにはどうすればよいですか?
A ggsave("plot.png", dpi = 300, width = 8, height = 6)、印刷の標準は300 dpiです。

📖 まとめ


📝 練習問題

  1. 基本演習:データフレーム(行数10、x値とy値の2列)を作成し、ggplot + geom_point + labs + theme_minimal を使用して散布図を描画し、aes() において color = "red"(内部)と color = "red"(外部)の違いを確認してください。

  2. 基本演習mtcars データセット(wtmpg)を使用して散布図を作成し、cylcolor = factor(cyl))に基づいてデータポイントを色分けし、labs() を使用してタイトルとテーマを追加してください。

  3. 基本演習:データフレーム(5つの都市と売上高)を作成し、geom_col() を使用して棒グラフを描画し、reorder(city, sales) を使ってデータを並べ替え、並べ替えの結果を確認してください。

  4. 応用演習:生徒30名のクラス4の得点をシミュレートし、geom_boxplot() を使用してクラス4の得点分布グラフを作成し、fill = class で塗りつぶしの色を指定し、theme_minimal() でテーマを追加してください。

  5. 課題mtcars を使用して、6つの図を作成してください(par(mfrow) スタイルと ggplot2 を組み合わせて)。① 重量(wt)対燃費(mpg)の散布図 ② 重量の分布を示すヒストグラム ③ 燃費の箱ひげ図 ④ シリンダーごとの重量対燃費 ⑤ カラーマッピングされた散布図 ⑥ テーマの完全なカスタマイズ。6つの図をPDFとして保存してください。

Web-Tutorial.com

Web-Tutorial 技術チーム

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

100%