📊
CHAPTER 03

美しい可視化アート

ggplot2で創造する美しいデータビジュアライゼーション。Grammar of Graphicsの理念を理解し、データの物語を美しく、効果的に伝えるグラフィックを作成する技術をマスターしよう。

ggplot2とは?

ggplot2は「Grammar of Graphics」の理念に基づいて設計された、革新的なデータ可視化パッケージです。グラフを構成要素に分解し、それらを組み合わせることで、無限の表現力を実現します。

従来のグラフ作成ツールとは異なり、ggplot2では「何を見せるか」「どう見せるか」を明確に分離し、論理的で美しいビジュアライゼーションを作成できます。

ggplot2_setup.R
# ggplot2の読み込み(tidyverseに含まれる) library(ggplot2) library(dplyr) # サンプルデータの作成 sample_data <- data.frame( x = c(1, 2, 3, 4, 5), y = c(2, 5, 3, 8, 7), category = c("A", "B", "A", "B", "A") ) # 最初のggplotグラフ ggplot(sample_data, aes(x = x, y = y)) + geom_point(size = 3, color = "#00ffff") + theme_minimal()

🎨 出力結果

x y 2 3 4 5 2 4 6 8

Grammar of Graphics

ggplot2の核心は「Grammar of Graphics」です。これは、グラフを以下の7つの要素に分解して考える理論的フレームワークです:

  1. Data - 可視化するデータセット
  2. Aesthetics - データを視覚的属性(x, y, color, size等)にマッピング
  3. Geometries - データの幾何学的表現(点、線、棒等)
  4. Facets - サブプロット作成
  5. Statistics - データの統計的変換
  6. Coordinates - 座標系の定義
  7. Themes - グラフの外観
grammar_structure.R
# Grammar of Graphicsの基本構造 ggplot( data = your_data, # 1. Data mapping = aes(x = var1, y = var2) # 2. Aesthetics ) + geom_point() + # 3. Geometries facet_wrap(~category) + # 4. Facets stat_smooth() + # 5. Statistics coord_cartesian() + # 6. Coordinates theme_minimal() # 7. Themes

ジオメトリ:データの形

ジオメトリ(geom)は、データを視覚的に表現する方法を決定します。ggplot2には30以上のgeomが用意されており、用途に応じて適切なものを選択できます。

geom_point()

散布図を作成します。2つの連続変数の関係を調べるのに最適です。

geom_point(aes(x, y, color, size))

geom_line()

線グラフを作成します。時系列データや連続性のあるデータの変化を表現します。

geom_line(aes(x, y, color, linetype))

geom_bar()

棒グラフを作成します。カテゴリカルデータの頻度や量を比較するのに使用します。

geom_bar(aes(x, fill), stat = "count")

geom_histogram()

ヒストグラムを作成します。連続変数の分布を視覚化するのに最適です。

geom_histogram(aes(x, fill), bins = 30)

geom_boxplot()

箱ひげ図を作成します。データの分布、外れ値、四分位数を一目で把握できます。

geom_boxplot(aes(x, y, fill))

geom_density()

密度プロットを作成します。データの分布を滑らかな曲線で表現します。

geom_density(aes(x, fill), alpha = 0.7)

🔶 geom_point(): 散布図の作成

scatter_plot_example.R
# mtcarsデータで馬力と燃費の関係を調べる library(ggplot2) # 基本的な散布図 p1 <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point(size = 3, color = "#00ffff") + labs(title = "馬力と燃費の関係", x = "馬力 (hp)", y = "燃費 (mpg)") + theme_dark() # 気筒数で色分けした散布図 p2 <- ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) + geom_point(size = 4, alpha = 0.8) + scale_color_manual(values = c("#ff1493", "#00ffff", "#39ff14")) + labs(title = "気筒数別馬力と燃費", x = "馬力 (hp)", y = "燃費 (mpg)", color = "気筒数") + theme_dark() print(p2)

🎨 出力結果

気筒数別馬力と燃費 馬力 (hp) 燃費 (mpg) 4気筒 6気筒 8気筒 100 200 300 10 20 30 35

📈 geom_line(): 時系列データの可視化

line_plot_example.R
# 時系列データの作成と可視化 library(ggplot2) library(dplyr) # サンプルの売上データ sales_data <- data.frame( month = 1:12, product_A = c(120, 135, 158, 142, 168, 195, 210, 198, 185, 172, 165, 148), product_B = c(95, 108, 125, 140, 155, 178, 192, 205, 220, 235, 248, 260) ) # データをlong形式に変換 sales_long <- sales_data %>% tidyr::pivot_longer(cols = starts_with("product"), names_to = "product", values_to = "sales") # 線グラフで売上推移を可視化 ggplot(sales_long, aes(x = month, y = sales, color = product)) + geom_line(size = 2, alpha = 0.8) + geom_point(size = 3) + scale_color_manual(values = c("#ff1493", "#00ffff")) + scale_x_continuous(breaks = 1:12, labels = paste0(1:12, "月")) + labs(title = "製品別売上推移 (2023年)", x = "月", y = "売上 (万円)", color = "製品") + theme_dark() + theme(panel.grid.major = element_line(color = "#333"))

🎨 出力結果

製品別売上推移 (2023年) 売上 (万円) product_A product_B 1月 3月 5月 7月 9月 11月 100 150 200 250 300

美学マッピング

美学(aesthetics)は、データの値を視覚的属性にマッピングする方法を定義します。色、サイズ、形、透明度などを使って、データに追加の次元を与えることができます。

効果的な美学マッピングは、データの隠れたパターンや関係性を浮き彫りにし、視聴者の理解を深めます。

aesthetics_advanced.R
# 複雑な美学マッピングの例 complex_plot <- ggplot(mtcars, aes(x = wt, # x軸: 重量 y = mpg, # y軸: 燃費 color = hp, # 色: 馬力(連続値) size = qsec, # サイズ: 加速性能 shape = factor(cyl) # 形: 気筒数 ) ) + geom_point(alpha = 0.8) + scale_color_gradient( low = "blue", high = "red", name = "馬力" ) + scale_size_continuous( range = c(2, 8), name = "1/4マイル時間" ) + labs( title = "自動車の性能総合分析", subtitle = "重量、燃費、馬力、加速性能、気筒数の関係", x = "重量 (1000 lbs)", y = "燃費 (mpg)", shape = "気筒数" ) + theme_minimal() + theme( plot.title = element_text(size = 16, face = "bold"), legend.position = "bottom" )

🎨 出力結果: 5次元データの統合可視化

自動車の性能総合分析 重量、燃費、馬力、加速性能、気筒数の関係 重量 (1000 lbs) 燃費 (mpg) 気筒数: 4気筒 6気筒 8気筒 馬力: 加速性能: 速い 通常 遅い 2 3 4 5 6 10 20 30 40 50

このように、一つのグラフで5次元の情報(x, y, color, size, shape)を同時に表現することで、データの複雑な関係性を一目で理解できるようになります。効果的な美学マッピングにより、以下のパターンが読み取れます:

  • 重量と燃費: 負の相関関係(重い車ほど燃費が悪い)
  • 気筒数の影響: 8気筒車は重く、燃費が悪い傾向
  • 馬力と色: 赤い点(高馬力)ほど燃費が悪い
  • サイズと加速: 大きい点ほど加速が遅い

実践的なグラフ作成

ggplot2の真価は、実際のデータを使って美しく洞察に富んだグラフを作成することにあります。ここでは、よく使われるグラフパターンと、プロフェッショナルな仕上げのテクニックを学びましょう。

時系列データの可視化

時系列データは、ビジネスや研究において最も重要なデータタイプの一つです。トレンド、季節性、異常値を効果的に可視化する方法を見てみましょう。

timeseries_analysis.R
# 時系列データの準備 library(tidyverse) library(lubridate) # サンプル売上データの作成 sales_ts <- tibble( date = seq(as.Date("2020-01-01"), as.Date("2023-12-31"), by = "month"), product_a = cumsum(rnorm(48, mean = 50, sd = 20)) + 1000, product_b = cumsum(rnorm(48, mean = 30, sd = 15)) + 800, product_c = cumsum(rnorm(48, mean = 25, sd = 12)) + 600 ) %>% pivot_longer( cols = starts_with("product"), names_to = "product", values_to = "sales" ) # 美しい時系列グラフの作成 timeseries_plot <- ggplot(sales_ts, aes(x = date, y = sales, color = product)) + geom_line(size = 1.2, alpha = 0.8) + geom_point(size = 2, alpha = 0.6) + scale_x_date( date_breaks = "6 months", date_labels = "%Y年%m月", expand = expansion(mult = c(0.02, 0.02)) ) + scale_y_continuous( labels = scales::comma_format(suffix = "万円"), expand = expansion(mult = c(0, 0.1)) ) + scale_color_manual( values = c("product_a" = "#00ffff", "product_b" = "#ff00ff", "product_c" = "#39ff14"), labels = c("製品A", "製品B", "製品C") ) + labs( title = "製品別売上高の推移", subtitle = "2020年1月〜2023年12月", x = "年月", y = "売上高", color = "製品", caption = "データ:社内売上システム" ) + theme_minimal() + theme( axis.text.x = element_text(angle = 45, hjust = 1), legend.position = "bottom", plot.title = element_text(size = 16, face = "bold") )

分布の比較と統計可視化

データの分布を理解することは、統計分析の基本です。複数グループの分布を効果的に比較する方法を学びましょう。

distribution_analysis.R
# 分布分析用データの準備 survey_data <- tibble( age_group = rep(c("20代", "30代", "40代", "50代"), each = 250), income = c( rnorm(250, mean = 350, sd = 80), # 20代 rnorm(250, mean = 450, sd = 100), # 30代 rnorm(250, mean = 550, sd = 120), # 40代 rnorm(250, mean = 600, sd = 150) # 50代 ), satisfaction = sample(c("低", "中", "高"), 1000, replace = TRUE) ) # 複合的な分布可視化 distribution_plot <- ggplot(survey_data, aes(x = age_group, y = income)) + geom_violin( aes(fill = age_group), alpha = 0.7, scale = "width" ) + geom_boxplot( width = 0.2, alpha = 0.9, outlier.color = "red", outlier.size = 2 ) + stat_summary( fun = mean, geom = "point", color = "white", size = 3, shape = 18 ) + scale_fill_manual( values = c("#00ffff", "#39ff14", "#ff6600", "#ff00ff") ) + scale_y_continuous( labels = scales::comma_format(suffix = "万円") ) + labs( title = "年代別年収分布の比較", subtitle = "バイオリンプロット + 箱ひげ図 + 平均値", x = "年代", y = "年収", fill = "年代" ) + theme_minimal() + theme(legend.position = "none")

相関関係とパターンの発見

散布図は変数間の関係を理解するための最も強力なツールの一つです。回帰線、信頼区間、グループ分けを組み合わせた高度な分析を行いましょう。

correlation_analysis.R
# 相関分析用データ(mtcarsを拡張) car_data <- mtcars %>% rownames_to_column("model") %>% as_tibble() %>% mutate( transmission = ifelse(am == 1, "マニュアル", "オートマ"), efficiency_class = case_when( mpg >= 25 ~ "高効率", mpg >= 20 ~ "中効率", TRUE ~ "低効率" ) ) # 高度な散布図の作成 correlation_plot <- ggplot(car_data, aes(x = wt, y = mpg)) + # 背景の密度等高線 stat_density_2d(alpha = 0.3, color = "gray70") + # 回帰線と信頼区間 geom_smooth( method = "lm", color = "#ff00ff", fill = "#ff00ff", alpha = 0.2 ) + # データポイント geom_point( aes(color = transmission, size = hp, shape = efficiency_class), alpha = 0.8 ) + # ラベル付け(outlierのみ) geom_text( data = car_data %>% filter(mpg > 30 | wt > 5), aes(label = model), nudge_y = 1, size = 3, color = "white" ) + scale_color_manual( values = c("マニュアル" = "#00ffff", "オートマ" = "#39ff14") ) + scale_size_continuous(range = c(3, 8)) + labs( title = "自動車の重量と燃費の関係", subtitle = "変速機タイプ、馬力、効率クラス別分析", x = "重量 (1000 lbs)", y = "燃費 (mpg)", color = "変速機", size = "馬力", shape = "効率クラス" ) + theme_dark() + theme( plot.background = element_rect(fill = "black"), panel.background = element_rect(fill = "gray10"), legend.position = "bottom" )

ファセットによる多次元分析

ファセットは、データの複数の側面を同時に可視化する強力な機能です。Small Multiplesの原理により、複雑なパターンを理解しやすくします。

facet_analysis.R
# 複雑なビジネスデータのシミュレーション business_data <- expand_grid( region = c("東京", "大阪", "名古屋", "福岡"), quarter = c("Q1", "Q2", "Q3", "Q4"), product_category = c("電子機器", "家具", "衣料品") ) %>% mutate( sales = case_when( region == "東京" ~ rnorm(n(), mean = 1500, sd = 300), region == "大阪" ~ rnorm(n(), mean = 1200, sd = 250), region == "名古屋" ~ rnorm(n(), mean = 800, sd = 200), TRUE ~ rnorm(n(), mean = 600, sd = 150) ), profit_margin = case_when( product_category == "電子機器" ~ runif(n(), 0.15, 0.25), product_category == "家具" ~ runif(n(), 0.30, 0.45), TRUE ~ runif(n(), 0.50, 0.70) ) ) # ファセットを活用した多次元可視化 facet_plot <- ggplot(business_data, aes(x = quarter, y = sales)) + geom_col( aes(fill = product_category), position = "dodge", alpha = 0.8 ) + geom_text( aes(label = scales::comma(sales, accuracy = 1), group = product_category), position = position_dodge(width = 0.9), vjust = -0.5, size = 3, color = "white" ) + facet_wrap(~region, scales = "free_y", ncol = 2) + scale_fill_manual( values = c("電子機器" = "#00ffff", "家具" = "#ff6600", "衣料品" = "#39ff14") ) + scale_y_continuous( labels = scales::comma_format(suffix = "万円") ) + labs( title = "地域別・四半期別・商品カテゴリ別売上分析", subtitle = "複数次元での売上パフォーマンス比較", x = "四半期", y = "売上高", fill = "商品カテゴリ" ) + theme_minimal() + theme( strip.text = element_text(size = 12, face = "bold"), legend.position = "bottom" )

ファセット:多次元データの分割表示

ファセットは、データをサブグループに分割して複数のサブプロットを作成する強力な機能です。パターンの比較や、カテゴリ別の傾向を同時に把握することができます。

📊 facet_wrap(): 1変数での分割

facet_wrap_example.R
# 気筒数別の燃費と馬力の関係 library(ggplot2) facet_plot <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point(aes(color = factor(am)), size = 3, alpha = 0.7) + geom_smooth(method = "lm", se = FALSE, color = "#39ff14", size = 1.2) + facet_wrap(~cyl, scales = "free", ncol = 3) + scale_color_manual( values = c("0" = "#ff1493", "1" = "#00ffff"), labels = c("AT", "MT") ) + labs( title = "気筒数別:馬力と燃費の関係", subtitle = "トランスミッション別に色分け", x = "馬力 (hp)", y = "燃費 (mpg)", color = "トランスミッション" ) + theme_dark() + theme( strip.background = element_rect(fill = "#2a2a2a"), strip.text = element_text(color = "#00ffff", size = 12, face = "bold"), panel.grid = element_line(color = "#333") ) print(facet_plot)

🎨 出力結果

気筒数別:馬力と燃費の関係 トランスミッション別に色分け 4 馬力 燃費 6 馬力 8 馬力 AT MT

🔲 facet_grid(): 2変数での分割

facet_grid_example.R
# 気筒数×トランスミッションでのクロス分析 grid_plot <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point(aes(color = factor(gear)), size = 3, alpha = 0.8) + geom_smooth(method = "loess", se = TRUE, alpha = 0.2) + facet_grid(am ~ cyl, labeller = labeller(am = c("0" = "オートマ", "1" = "マニュアル"))) + scale_color_manual( values = c("3" = "#ff1493", "4" = "#00ffff", "5" = "#39ff14"), name = "ギア数" ) + labs( title = "トランスミッション×気筒数別:性能分析", x = "馬力 (hp)", y = "燃費 (mpg)" ) + theme_minimal() + theme( strip.text = element_text(size = 10, face = "bold") )

スケール:データマッピングの制御

スケールは、データの値を視覚的属性(位置、色、サイズなど)にマッピングする方法を制御します。適切なスケールの選択により、データの特性を効果的に伝えることができます。

🌈 カラースケール

color_scales_example.R
# 様々なカラースケールの使用例 library(ggplot2) library(viridis) # 連続値のカラーグラデーション continuous_color <- ggplot(mtcars, aes(x = wt, y = mpg, color = hp)) + geom_point(size = 4, alpha = 0.8) + scale_color_viridis_c( option = "plasma", name = "馬力\n(hp)", guide = guide_colorbar( barwidth = 1, barheight = 10, title.position = "top" ) ) + labs( title = "連続カラースケール:Viridis Plasma", x = "重量 (1000 lbs)", y = "燃費 (mpg)" ) + theme_dark() + theme(legend.position = "right") # カテゴリカルデータの色分け discrete_color <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + geom_point(size = 4) + scale_color_brewer( type = "qual", palette = "Set1", name = "気筒数" ) + labs(title = "カテゴリカルカラー:ColorBrewer Set1")

📏 軸スケール

axis_scales_example.R
# 軸の変換とカスタマイズ log_scale_plot <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point(aes(color = factor(cyl)), size = 3) + scale_x_log10( breaks = c(50, 100, 200, 400), labels = c("50hp", "100hp", "200hp", "400hp") ) + scale_y_continuous( breaks = seq(10, 35, 5), labels = function(x) paste0(x, " mpg"), limits = c(10, 35) ) + labs( title = "対数スケールを使用した軸変換", subtitle = "X軸:対数スケール、Y軸:線形スケール", x = "馬力 (対数スケール)", y = "燃費", color = "気筒数" ) + theme_minimal()

座標系:データの幾何学的表現

座標系は、データを平面上にどのように配置するかを決定します。デカルト座標系以外にも、極座標系や地図投影など、データの性質に応じた様々な座標系を選択できます。

coordinate_systems.R
# 極座標系を使用した円グラフ pie_data <- data.frame( category = c("製品A", "製品B", "製品C", "製品D"), value = c(30, 25, 25, 20) ) polar_plot <- ggplot(pie_data, aes(x = "", y = value, fill = category)) + geom_col(width = 1, color = "white", size = 2) + coord_polar(theta = "y", start = 0) + scale_fill_manual( values = c("#ff1493", "#00ffff", "#39ff14", "#ffd700") ) + labs( title = "極座標系による円グラフ", subtitle = "製品別市場シェア", fill = "製品" ) + theme_void() + theme( plot.title = element_text(hjust = 0.5, size = 16), plot.subtitle = element_text(hjust = 0.5, size = 12), legend.position = "bottom" ) # 軸の入れ替え flipped_plot <- ggplot(mtcars, aes(x = reorder(rownames(mtcars), mpg), y = mpg)) + geom_col(fill = "#00ffff", alpha = 0.8) + coord_flip() + labs( title = "軸入れ替えによる水平棒グラフ", x = "車種", y = "燃費 (mpg)" ) + theme_minimal() + theme(axis.text.y = element_text(size = 8))

統計変換:データの数学的分析

統計変換(stat)は、生データを数学的に変換して、データのパターンや傾向を可視化します。回帰線、密度推定、統計要約など、データサイエンスに不可欠な機能です。

📈 stat_smooth(): 回帰線と傾向

regression_analysis.R
# 様々な回帰モデルの比較 library(ggplot2) library(dplyr) # 線形回帰、LOESS、GAMモデルの比較 regression_plot <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point(alpha = 0.7, size = 3, color = "white") + # 線形回帰 stat_smooth(method = "lm", color = "#ff1493", se = TRUE, alpha = 0.2, size = 1.5) + # LOESS回帰 stat_smooth(method = "loess", color = "#00ffff", se = FALSE, size = 1.5, linetype = "dashed") + # GAM回帰 stat_smooth(method = "gam", color = "#39ff14", se = FALSE, size = 1.5, linetype = "dotted") + labs( title = "回帰モデルの比較分析", subtitle = "線形(LM), LOESS, GAMの異なるアプローチ", x = "馬力 (hp)", y = "燃費 (mpg)" ) + theme_dark() + theme( plot.background = element_rect(fill = "black"), panel.background = element_rect(fill = "#1a1a1a"), panel.grid = element_line(color = "#333") )

🎨 出力結果

回帰モデルの比較分析 線形(LM), LOESS, GAMの異なるアプローチ 馬力 (hp) 燃費 (mpg) Linear (LM) LOESS GAM

📊 stat_summary(): 統計要約

statistical_summary.R
# カスタム統計要約の作成 summary_plot <- ggplot(mtcars, aes(x = factor(cyl), y = mpg)) + # 生データポイント geom_jitter(alpha = 0.6, width = 0.2, color = "white") + # 平均値と標準誤差 stat_summary( fun = mean, fun.min = function(x) mean(x) - sd(x), fun.max = function(x) mean(x) + sd(x), geom = "pointrange", color = "#ff1493", size = 1.2 ) + # 中央値と四分位数 stat_summary( fun = median, fun.min = function(x) quantile(x, 0.25), fun.max = function(x) quantile(x, 0.75), geom = "pointrange", color = "#00ffff", size = 1.2, position = position_nudge(x = 0.1) ) + labs( title = "カスタム統計要約の比較", subtitle = "平均±SD (ピンク) vs 中央値±IQR (シアン)", x = "気筒数", y = "燃費 (mpg)" ) + theme_dark()

プロフェッショナルなテーマ設計

グラフの見た目は、データの理解と信頼性に大きく影響します。ggplot2の強力なテーマシステムを活用して、用途に応じた美しいグラフを作成しましょう。

カスタムテーマの作成

組織のブランドに合わせたカスタムテーマを作成することで、一貫性のある美しい可視化を実現できます。

custom_themes.R
# カスタム企業テーマの定義 theme_corporate <- function(base_size = 12, base_family = "") { theme_minimal(base_size = base_size, base_family = base_family) + theme( # 全体の背景 plot.background = element_rect(fill = "white", color = NA), panel.background = element_rect(fill = "white", color = NA), # グリッド線 panel.grid.major = element_line(color = "gray90", size = 0.5), panel.grid.minor = element_blank(), # 軸とタイトル axis.line = element_line(color = "gray30", size = 0.5), axis.ticks = element_line(color = "gray30", size = 0.3), axis.text = element_text(color = "gray20", size = rel(0.9)), axis.title = element_text(color = "gray10", size = rel(1.0)), # プロットタイトル plot.title = element_text( color = "#2c3e50", size = rel(1.4), face = "bold", hjust = 0, margin = margin(b = 20) ), plot.subtitle = element_text( color = "gray40", size = rel(1.1), hjust = 0, margin = margin(b = 20) ), plot.caption = element_text( color = "gray50", size = rel(0.8), hjust = 1, margin = margin(t = 20) ), # 凡例 legend.background = element_rect(fill = "white", color = "gray80"), legend.key = element_rect(fill = "white", color = NA), legend.text = element_text(color = "gray20"), legend.title = element_text(color = "gray10", face = "bold"), # ファセット strip.background = element_rect(fill = "#ecf0f1", color = "gray80"), strip.text = element_text(color = "#2c3e50", face = "bold") ) } # ダークモード テーマ theme_dark_pro <- function(base_size = 12) { theme_void(base_size = base_size) + theme( plot.background = element_rect(fill = "#1a1a1a", color = NA), panel.background = element_rect(fill = "#2d2d2d", color = NA), panel.grid.major = element_line(color = "#404040", size = 0.3), panel.grid.minor = element_line(color = "#333333", size = 0.1), axis.text = element_text(color = "#e0e0e0"), axis.title = element_text(color = "#f0f0f0"), plot.title = element_text(color = "#00ffff", face = "bold"), plot.subtitle = element_text(color = "#cccccc"), legend.text = element_text(color = "#e0e0e0"), legend.title = element_text(color = "#f0f0f0") ) } # テーマ適用例 corporate_example <- ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point(size = 3, alpha = 0.7) + geom_smooth(method = "lm", se = FALSE, color = "#e74c3c") + labs( title = "エンジン排気量と燃費の関係", subtitle = "車種クラス別の分析結果", x = "エンジン排気量 (L)", y = "高速道路燃費 (mpg)", color = "車種クラス", caption = "データソース: EPA燃費データベース" ) + theme_corporate() + guides(color = guide_legend(title.position = "top"))

これらの実践例により、ggplot2を使った本格的なデータ可視化の技術を身につけることができます。美しいグラフは、データの物語を効果的に伝え、意思決定をサポートする強力なツールになります。

高度なテクニック

ggplot2の真の力は、基本要素を組み合わせて革新的なビジュアライゼーションを作成することにあります。ファセット、統計変換、カスタムテーマを駆使して、データの物語を効果的に伝えましょう。

advanced_visualization.R
# 多面的なデータ分析 library(dplyr) # データの前処理と可視化を組み合わせ advanced_analysis <- mtcars %>% mutate( efficiency = case_when( mpg >= 25 ~ "High", mpg >= 20 ~ "Medium", TRUE ~ "Low" ), transmission = ifelse(am == 1, "Manual", "Automatic") ) %>% ggplot(aes(x = wt, y = hp)) + geom_point(aes(color = efficiency, shape = transmission), size = 3, alpha = 0.8) + geom_smooth(method = "lm", se = FALSE, color = "darkgray", linetype = "dashed") + facet_wrap(~factor(cyl), ncol = 3, labeller = labeller(.default = "気筒")) + scale_color_manual( values = c("High" = "#00ff41", "Medium" = "#ffaa00", "Low" = "#ff0040") ) + labs( title = "自動車性能の多次元分析", subtitle = "重量、馬力、燃費効率、変速機タイプ、気筒数の関係", x = "重量 (1000 lbs)", y = "馬力 (hp)", color = "燃費効率", shape = "変速機" ) + theme_dark() + theme( plot.background = element_rect(fill = "black"), panel.background = element_rect(fill = "gray10"), text = element_text(color = "white"), plot.title = element_text(size = 16, face = "bold", color = "cyan"), strip.text = element_text(color = "white", face = "bold") )