R ggplot2 のテーマとスタイル設定:`theme` の完全ガイド
ggplot2 のデフォルトテーマである
theme_gray()はすでにかなり優れていますが、「出版物レベルの品質」を持つグラフを作成するには、テーマを微調整する必要があります。このレッスンでは、ggplot2のテーマシステムについて詳しく見ていきます。8つの組み込みテーマから始まり、theme()からlabs、scaleへの微調整を経て、ggsaveによる高解像度出力に至るまでを解説します。
このレッスンを修了すると、テキスト、色、凡例、余白、軸などを完全に制御し、あらゆるggplot2のプロットを「出版可能な」水準まで微調整できるようになります。
1. 学習内容
- 8つの組み込みggplot2テーマ
- theme() の要素ツリー (element_text/line/rect)
- labs() の完全なラベル
- スケールカラー/塗りつぶし色の対応関係
- テーマテンプレート(ggthemes / hrbrthemes)
- ggsave() HDで保存
- 実践ガイド:出版物レベルのグラフのカスタマイズ
2. 「プロ用チャート」の物語
(1) 課題:デフォルトの画像が「学校っぽい」印象が強すぎる
ボブはggplot2を使ってグラフを作成したが、マネージャーは「これは投資家向けのレポートなのに、あまりにも地味すぎる」と言った。
(2) ggplot2 の可視化オプション
library(ggplot2)
library(hrbrthemes) # Professional Theme Packages
p <- ggplot(sales, aes(x = quarter, y = sales, color = city, group = city)) +
geom_line(linewidth = 1.2) +
geom_point(size = 3) +
scale_color_brewer(palette = "Set1") +
labs(
title = "2024 Q1-Q4 Sales Trends",
subtitle = "Data Source: Sales System | Chart: Analyst Team",
caption = "Unit: 10,000 yuan",
x = "Quarter", y = "Sales (10,000 yuan)",
color = "City"
) +
theme_minimal(base_size = 12) +
theme(
plot.title = element_text(face = "bold", size = 16),
plot.subtitle = element_text(color = "gray50"),
legend.position = "top",
panel.grid.minor = element_blank()
)
ggsave("professional_report.png", p, width = 10, height = 6, dpi = 300)
たった3行のコードで、出版レベルの高品質なグラフを作成。
3. 8 標準テーマ
(1) テーマの比較
| テーマ | スタイル | 適した場面 |
|---|---|---|
theme_gray() |
デフォルト(背景色:グレー) | 一般 |
theme_bw() |
白黒 | 学術論文 |
theme_minimal() |
ミニマリスト(最もよく使われる) | レポート・プレゼンテーション |
theme_classic() |
クラシック(グリッドなし) | アカデミック |
theme_void() |
空白 | 地図・図 |
theme_light() |
明るい背景 | デモ |
theme_dark() |
暗い背景 | ダークテーマ |
theme_test() |
テスト用 | デバッグ |
(2) 実環境での比較
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
p + theme_gray() # Default
p + theme_minimal() # Minimalism
p + theme_bw() # Black and White
p + theme_classic() # Classic
p + theme_light() # Light-colored
p + theme_dark() # Dark
p + theme_void() # Blank
ベースサイズ/ベースファミリー
# Set the font size globally
p + theme_minimal(base_size = 14)
# Set the Global Font
p + theme_minimal(base_family = "SimHei") # Chinese
4. theme() の要素ツリー
(1) 要素の構造
graph TB
A[theme Element] --> B[plot Full Image]
A --> C[axis Coordinate Axes]
A --> D[legend Legend]
A --> E[panel Panel]
A --> F[strip Facet Labels]
A --> G[title Title]
B --> H[plot.title]
B --> I[plot.background]
C --> J[axis.title]
C --> K[axis.text]
C --> L[axis.line]
D --> M[legend.title]
D --> N[legend.text]
D --> O[legend.position]
E --> P[panel.background]
E --> Q[panel.grid]
F --> R[strip.text]
F --> S[strip.background]
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
(2) element_ 関数の 4 種類
| 機能 | 目的 | 用途 |
|---|---|---|
element_text() |
テキスト | タイトル、軸ラベル、目盛りのテキスト |
element_line() |
線 | グリッド線、軸線 |
element_rect() |
長方形 | 背景、枠線、パネル |
element_blank() |
非表示 | 任意の要素 |
(3) element_text() のテキストパラメータ
theme(
plot.title = element_text(
size = 16, # Font size
face = "bold", # Bold/italics (plain/bold/italic/bold.italic)
color = "blue", # Color
family = "SimHei",# Font
hjust = 0.5, # Horizontal Alignment (0=left, 1=right, 0.5=center)
vjust = 0.5 # Vertical Alignment
)
)
(4) element_line() の線に関するパラメータ
theme(
panel.grid.major = element_line(
color = "gray80",
linewidth = 0.5,
linetype = "dashed" # solid/dashed/dotted
),
panel.grid.minor = element_blank(), # Hide Secondary Grid
axis.line = element_line(color = "black", linewidth = 0.8)
)
(5) element_rect() の矩形パラメータ
theme(
panel.background = element_rect(
fill = "lightyellow",
color = "black",
linewidth = 0.5
),
plot.background = element_rect(fill = "white")
)
(6) element_blank() 非表示
theme(
panel.grid = element_blank(), # Hide All Grids
axis.ticks = element_blank(), # Hide Scale
legend.position = "none" # Hide Legend (Note: No element_blank)
)
5. 共通テーマの微調整
(1) 文字サイズ
p + theme(
plot.title = element_text(size = 18, face = "bold"),
plot.subtitle = element_text(size = 12, color = "gray50"),
axis.title = element_text(size = 12),
axis.text = element_text(size = 10),
legend.title = element_text(size = 11),
legend.text = element_text(size = 10)
)
(2) グリッド線
p + theme(
panel.grid.major = element_line(color = "gray90"),
panel.grid.minor = element_blank(), # Hide Secondary Grid (More concise)
panel.border = element_rect(color = "black", fill = NA, linewidth = 0.5)
)
(3) 凡例の位置
# 4 every corner
p + theme(legend.position = "top")
p + theme(legend.position = "bottom")
p + theme(legend.position = "left")
p + theme(legend.position = "right")
# Hide
p + theme(legend.position = "none")
# Coordinate Positioning (In the figure)
p + theme(legend.position = c(0.8, 0.2)) # 80% x, 20% y
(4) 座標軸
p + theme(
axis.line = element_line(color = "black", linewidth = 0.8),
axis.ticks = element_line(color = "black"),
axis.title.x = element_text(margin = margin(t = 10)), # X Move the axis title down
axis.title.y = element_text(margin = margin(r = 10)) # Y Shift the axis title to the left
)
6. labs() のドキュメントを完成させる
(1) すべてのタグ
p + labs(
title = "Main Title",
subtitle = "Subtitle",
caption = "Data Sources",
x = "X Axis",
y = "Y Axis",
color = "Color Mapping", # Corresponding aes(color)
fill = "Fill Mapping", # Corresponding aes(fill)
shape = "Shape Mapping",
size = "Size Mapping"
)
(2) 数式タグ
# For use in formulas quote() or expression
p + labs(
x = quote(x[i]),
y = expression(paste("Concentration (", mu, "g/mL)"))
)
7. scale_color / scale_fill の色
(1) 離散的な色(カテゴリ変数)
# 1. Specify manually
p + scale_color_manual(values = c("red", "blue", "green", "orange"))
# 2. ColorBrewer Color Palette
p + scale_color_brewer(palette = "Set1") # Classic 9 colors
p + scale_color_brewer(palette = "Set2") # Gentle 8 colors
p + scale_color_brewer(palette = "Dark2") # Dark 8 colors
p + scale_color_brewer(palette = "Pastel1") # Light-colored 9 colors
# 3. viridis (Color-blind-friendly, Recommended)
library(viridis)
p + scale_color_viridis_d() # Discrete
p + scale_color_viridis_c() # Consecutive
(2) 連続色(連続変数)
# Gradient
p + scale_color_gradient(low = "blue", high = "red")
p + scale_color_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0)
p + scale_color_gradientn(colours = rainbow(7))
(3) 実践的な応用:プロフェッショナルな配色
# 4 Class Classification
p + scale_color_brewer(palette = "Set1")
# 8 Class Classification
p + scale_color_brewer(palette = "Set2")
# Color-blind-friendly
p + scale_color_viridis_d()
# Academic/Serious
p + scale_color_manual(values = c("#1f77b4", "#ff7f0e", "#2ca02c"))
8. 専門テーマパッケージ
(1) ggthemesの8つのテーマ
install.packages("ggthemes")
library(ggthemes)
p + theme_economist() # The Economist
p + theme_wsj() # The Wall Street Journal
p + theme_fivethirtyeight() # FiveThirtyEight
p + theme_hc() # Highcharts
p + theme_tufte() # Tufte Minimalism
p + theme_stata() # Stata
p + theme_solarized() # Solarized
p + theme_excel() # Excel Style
(2) hrbrthemes の商用テーマ
install.packages("hrbrthemes")
library(hrbrthemes)
p + theme_ipsum() # ipsum Typographic Style
p + theme_ft_rc() # The Financial Times
(3) カスタムテーマ(一度定義すれば、どこでも使用可能)
# Custom Themes
my_theme <- theme_minimal(base_size = 12) +
theme(
plot.title = element_text(face = "bold", size = 14),
panel.grid.minor = element_blank(),
legend.position = "bottom"
)
# Global Use
ggplot(df, aes(x, y)) + geom_point() + my_theme
9. ggsave() 高解像度で保存
(1) 4つの主要パラメータ
ggsave(
filename, # File Name
plot = last_plot(), # Graph Object (Default: Last Image)
width = 8, # Width
height = 6, # High
units = "in", # Unit in/cm/mm
dpi = 300 # Resolution
)
(2) 実践的な応用
# PNG Printing Standard (300 dpi)
ggsave("report.png", width = 8, height = 6, dpi = 300)
# High-Definition Screen (150 dpi)
ggsave("screen.png", width = 1920, height = 1080, units = "px", dpi = 150)
# PDF For a thesis (Vector)
ggsave("paper.pdf", width = 8, height = 6)
# Chinese Title (Avoid garbled characters)
ggsave("Chinese.png", width = 8, height = 6, dpi = 300)
(3) さまざまな形式
| 形式 | 拡張子 | 用途 |
|---|---|---|
| PNG | .png |
Web/ドキュメント (最も一般的) |
.pdf |
学位論文(ベクトル) | |
| SVG | .svg |
Webベクターグラフィックス |
| JPEG | .jpg |
写真(グラフィック用途には不向き) |
| TIFF | .tiff |
印刷 |
# Vector Graphics (Unlimited Clear Zoom)
ggsave("vector.svg", width = 8, height = 6)
ggsave("vector.pdf", width = 8, height = 6)
10. 完全な例:プロフェッショナルで、出版物レベルの品質を誇るグラフ
以下は、このレッスンで取り上げたすべてのトピックを結びつける完全なワークフローの例です。
▶ サンプル:4都市の販売実績—出版物レベルのグラフ
# ============================================
# 4 City Sales: Publication-Quality Charts
# Features: Complete Customization from Default to Professional Level
# ============================================
library(ggplot2)
library(dplyr)
library(tidyr)
library(patchwork)
library(hrbrthemes)
# 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") |>
mutate(
total = sum(sales),
pct = round(sales / total * 100, 1)
)
# 2. Custom Themes
my_theme <- theme_minimal(base_size = 12) +
theme(
plot.title = element_text(face = "bold", size = 16, hjust = 0,
margin = margin(b = 5)),
plot.subtitle = element_text(color = "gray40", size = 11,
margin = margin(b = 15)),
plot.caption = element_text(color = "gray50", size = 9,
hjust = 1, margin = margin(t = 10)),
axis.title = element_text(size = 11),
axis.text = element_text(size = 10, color = "gray30"),
panel.grid.major = element_line(color = "gray90", linewidth = 0.3),
panel.grid.minor = element_blank(),
legend.position = "top",
legend.title = element_text(size = 11),
legend.text = element_text(size = 10),
plot.background = element_rect(fill = "white", color = NA)
)
# 3. Plot 1: Line Trend (Professional Edition)
p1 <- ggplot(sales_long, aes(x = quarter, y = sales, color = city, group = city)) +
geom_line(linewidth = 1.2) +
geom_point(size = 3.5, fill = "white", shape = 21, stroke = 1.5) +
scale_color_brewer(palette = "Set1", name = "City") +
scale_y_continuous(labels = scales::comma, expand = expansion(mult = 0.1)) +
labs(
title = "2024 Annual Quarterly Sales Trends",
subtitle = "4 First-tier cities 4 Quarterly Sales Data",
caption = "Data Source: Sales System | Chart: Analyst Team",
x = NULL, y = "Sales (10,000 yuan)"
) +
my_theme
# 4. Plot 2: Bar Chart Comparison (Professional Edition)
total_sales <- sales_wide |>
mutate(total = Q1 + Q2 + Q3 + Q4) |>
arrange(desc(total)) |>
mutate(city = factor(city, levels = city))
p2 <- ggplot(total_sales, aes(x = city, y = total, fill = city)) +
geom_col(width = 0.7) +
geom_text(aes(label = scales::comma(total)), vjust = -0.5, size = 4) +
scale_fill_brewer(palette = "Set1", guide = "none") +
scale_y_continuous(labels = scales::comma,
expand = expansion(mult = c(0, 0.15))) +
labs(
title = "Annual Total Sales by City",
subtitle = "Sort by total sales in descending order",
x = NULL, y = "Total Sales (10,000 yuan)"
) +
my_theme
# 5. Plot 3: Stacked Columns (Professional Edition)
sales_long_ordered <- sales_long |>
left_join(total_sales |> select(city, total), by = "city") |>
mutate(city = factor(city, levels = total_sales$city))
p3 <- ggplot(sales_long_ordered, aes(x = city, y = sales, fill = quarter)) +
geom_col(position = "stack", width = 0.7) +
scale_fill_brewer(palette = "YlGnBu", name = "Quarter") +
labs(
title = "Quarterly Sales Breakdown by City",
subtitle = "Stacked bar chart showing quarterly contributions",
x = NULL, y = "Sales (10,000 yuan)"
) +
my_theme
# 6. Multi-Image Collage
combined <- (p1 / (p2 + p3)) +
plot_annotation(
title = "2024 4-City Comprehensive Sales Analysis",
theme = theme(plot.title = element_text(face = "bold", size = 18, hjust = 0.5))
)
print(combined)
# 7. Save Publication-Quality Images
ggsave("professional_report.png", combined,
width = 14, height = 12, dpi = 300)
ggsave("professional_report.pdf", combined,
width = 14, height = 12)
ggsave("professional_report.svg", combined,
width = 14, height = 12)
cat("\n=== Publishing-quality charts have been saved ===\n")
cat(" - professional_report.png (PNG 300dpi)\n")
cat(" - professional_report.pdf (PDF Vector)\n")
cat(" - professional_report.svg (SVG Vector)\n")
期待される成果物:出版物レベルの品質を備えたグラフ3セット(折れ線グラフ+棒グラフ+積み上げグラフ)。これには、中国語および英語のタイトル、プロ仕様の配色、明確なラベルが含まれること。
❓ よくある質問
theme_minimal Minimal(白い背景、薄い灰色のグリッド)、theme_bw Black and White(枠線あり、はっきりとしたグリッド)。theme(panel.grid.minor = element_blank())。これで画像がすっきりします。bottomまたはtopを、4つ以上の場合はrightを、他のグラフ内に埋め込まれた円グラフの場合はc(0.5, 0.5)を使用して配置してください。ggsave デフォルトは 300 dpi です。theme_minimal(base_family = "SimHei") (Windows)、"PingFang SC" (macOS)、または "WenQuanYi Zen Hei" (Linux)。📖 まとめ
- ggplot2 には 8つの組み込みテーマ があります:
theme_graytheme_bwtheme_minimaltheme_classicなど。 theme()要素ツリーは、7つの領域(プロット、軸、凡例、パネル、ストリップ、タイトル)に分かれています。- 4種類の要素関数:
element_textテキスト /element_line線 /element_rect長方形 /element_blank非表示 - テーマコアの微調整:
plot.titleaxis.titlelegend.positionpanel.gridlabs()すべてのタグを設定:titlesubtitlecaptionxycolorfill - カラー:
scale_color_brewer/scale_color_viridis_d/scale_color_manual - 専門トピックパック:
ggthemes(『エコノミスト』/『ウォール・ストリート・ジャーナル』)/hrbrthemes(ビジネス) ggsave("plot.png", dpi = 300)印刷用標準;ggsave("plot.pdf")ベクター- 出版物レベルのグラフ = テーマ + 色 + ラベル + フォントサイズ + ggsaveによる高解像度出力
📝 練習問題
-
基本演習:
mtcarsを使用してwt対mpgの散布図を作成し、4つのテーマtheme_minimal、theme_bw、theme_classic、およびtheme_voidを用いて、生成された散布図の違いを比較してください。比較のためにスクリーンショットを撮影してください。 -
基本演習:棒グラフを作成し、
theme()を使用して微調整を行います。① タイトルを太字、サイズ16に設定します。② 補助グリッド線を非表示にします。③ 凡例を下部に配置します。④ Y軸のタイトルを軸から10px離して配置します。 -
基本演習:
scale_color_brewer(palette = "Set1")とscale_color_brewer(palette = "Set2")を使って同じ画像を描き、スクリーンショットを撮って色の違いを比較してください。 -
応用演習:4つの都市の販売データをシミュレートし、以下のカスタマイズを施した、出版物レベルの完成度の高いグラフを作成してください:① カスタムテーマ ② 「labs」ラベルの完全な表示 ③ プロフェッショナルな配色 ④ 高解像度での保存。作成過程と結果の両方のスクリーンショットを保存してください。
-
課題:
ggthemesのtheme_economist()またはtheme_wsj()を使用して絵を描き、デフォルトのtheme_minimal()との違いを比較してください。画像をPNG形式とPDF形式の両方で保存してください(PDFでは、漢字を表示するためにCairo PDFデバイスを使用してください)。



