R ggplot2 クイックスタート: 素早く信頼できるチャートを作るレシピ集
問題
締め切りが厳しいとき、アナリストは一貫した R チャートを作成するのに苦労します。テンプレートなしで geoms・scales・themes を切り替えると、ノイズの多いビジュアルになり、同じ修正を何度も繰り返すことになります。
問題の深刻化
aesthetics の指定漏れ、不適切な凡例、色 scale の不一致によって、ステークホルダーを誤解させるチャートが生まれます。シグナルに集中する代わりに、デフォルト設定の微調整に時間が浪費されます。
解決策
aesthetics を明示的に保ち、データに基づく mapping と固定設定を分離し、クリーンな theme を適用するコンパクトな ggplot2 レシピ集を使います。以下のパターンは、最もよく求められるプロットタイプと、比較のために facet する方法をカバーしています。
散布図: 関係とトレンドライン
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3, alpha = 0.8) +
geom_smooth(method = "lm", se = FALSE, linewidth = 0.8) +
labs(color = "Cylinders", x = "Weight", y = "MPG") +
theme_minimal()折れ線: 時系列または順序付きカテゴリ
ggplot(economics, aes(x = date, y = unemploy)) +
geom_line(color = "#1f77b4", linewidth = 1) +
labs(x = "Date", y = "Unemployment") +
scale_x_date(date_breaks = "2 years", date_labels = "%Y") +
theme_minimal()棒グラフ: カウントまたは合計値
ggplot(diamonds, aes(x = cut, fill = cut)) +
geom_bar(width = 0.7, color = "white") +
labs(x = "Cut", y = "Count") +
theme_minimal() +
theme(legend.position = "none")箱ひげ図とバイオリンプロット: 分布の比較
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) +
geom_violin(alpha = 0.4, color = NA) +
geom_boxplot(width = 0.18, outlier.shape = NA, alpha = 0.8) +
labs(x = NULL, y = "Sepal Length") +
theme_minimal() +
theme(legend.position = "none")Facet による素早い比較
ggplot(diamonds, aes(carat, price, color = cut)) +
geom_point(alpha = 0.4, size = 1.5) +
facet_wrap(~ color) +
labs(x = "Carat", y = "Price") +
theme_light()Geom と主な用途
| Geom | データ型 | 適した用途 | コツ |
|---|---|---|---|
geom_point() | 数値 vs 数値 | 関係性・クラスタ | 色や shape をカテゴリに map し、トレンドには geom_smooth() を追加。 |
geom_line() | 順序付き x・数値 y | 時系列・シーケンス | group= でグループごとに 1 本ずつ線を保ち、ソートのミスを避ける。 |
geom_bar()(カウント) / geom_col()(事前集計) | カテゴリ | カウントや合計 | 割合を見せるときは position = "fill" を使用。 |
geom_boxplot() | カテゴリ vs 数値 | 中央値・IQR の比較 | ラベルが長い場合は coord_flip() と組み合わせる。 |
geom_violin() | カテゴリ vs 数値 | 分布形状の把握 | 四分位を見せるために箱ひげ図と組み合わせる。 |
geom_histogram() | 単一の数値 | 分布 | bins か binwidth を明示的に指定する。 |
Aesthetics と固定設定の違い
- データを map するときは
aes()の中で指定:aes(color = species)。 - 固定値を使うときは
aes()の外で指定:geom_point(color = "steelblue")。 - 値の書式やカラーパレットの制御には
scale_*関数を使う。
Theme とラベリングのチェックリスト
- クリーンなデフォルトには
theme_minimal()かtheme_light()から始める。 - 文脈を示すために
labs(title, subtitle, caption)を追加し、軸ラベルは短く保つ。 - 色が facet やラベルと重複する場合は、
theme(legend.position = "none")で冗長な凡例を隠す。 - 公開用には、
theme(text = element_text(size = 12))でフォントサイズを調整する。
スターターテンプレート
base_plot <- ggplot(data, aes(x = x_var, y = y_var)) +
geom_point(color = "#4e79a7", alpha = 0.7) +
labs(
title = "Headline metric",
x = "X axis",
y = "Y axis",
caption = "Source: internal data"
) +
theme_minimal()関連ガイド
- 描画前にデータをクリーンにする: R dplyr Data Wrangling Pipeline
- ヒートマップ専用のオプション: pheatmap in R
- ベースとなるテーブルを素早く作る: How to Create a Dataframe in R