📊
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)

📊 豊富な描画例:基本から応用まで

🫧 バブルチャート:3次元データの表現

bubble_chart_example.R
# バブルチャートで多次元データを表現 # バブルチャート = 散布図 + サイズによる第3の変数表現 library(ggplot2) # メインのグラフ作成ライブラリ library(dplyr) # データ操作用ライブラリ # 企業データの作成(実際のビジネス分析でよく使う指標) company_data <- data.frame( company = c("A社", "B社", "C社", "D社", "E社", "F社"), profit = c(15.2, 8.5, 22.3, 11.8, 18.7, 6.2), # 利益率(%) market_share = c(25, 45, 15, 30, 20, 35), # 市場シェア(%) employees = c(1200, 3500, 800, 2100, 1600, 950), # 従業員数 industry = c("Tech", "Manufacturing", "Finance", "Tech", "Retail", "Manufacturing") ) # バブルチャートの作成 # ggplot()でベースを作成 + aes()で変数をビジュアル要素にマッピング bubble_plot <- ggplot(company_data, aes( x = market_share, # X軸:市場シェア y = profit, # Y軸:利益率 size = employees, # サイズ:従業員数(バブルの大きさで表現) color = industry # 色:業界(カテゴリカル変数) )) + geom_point(alpha = 0.7, stroke = 2) + # alpha=透明度, stroke=境界線の太さ geom_text(aes(label = company), vjust = -1.2, color = "white", size = 4) + # 企業名ラベル追加 scale_size_continuous(range = c(5, 20), guide = "legend") + # サイズの範囲を5-20に設定 scale_color_manual( values = c("Tech" = "#00ffff", "Manufacturing" = "#ff6600", "Finance" = "#39ff14", "Retail" = "#ff1493") ) + labs( title = "企業パフォーマンス分析", subtitle = "市場シェア vs 利益率 (バブルサイズ:従業員数)", x = "市場シェア (%)", y = "利益率 (%)", size = "従業員数", color = "業界" ) + theme_dark() + theme( plot.background = element_rect(fill = "black"), legend.position = "bottom" ) print(bubble_plot)

🔶 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_tile(): ヒートマップで相関を可視化

heatmap_example.R
# 相関行列のヒートマップ # ヒートマップ = データを色の濃淡で表現する手法 library(ggplot2) # グラフ作成 library(reshape2) # データ形状変換(wide→long) # mtcarsの相関行列を計算(-1〜1の値、1に近いほど正の相関) corr_matrix <- cor(mtcars[, c("mpg", "hp", "wt", "qsec", "drat")]) corr_melted <- melt(corr_matrix) # ヒートマップの作成 # geom_tile()でタイル状の図形を描画、fill(塗り)で値を表現 heatmap_plot <- ggplot(corr_melted, aes( Var1, Var2, # X軸、Y軸(変数名) fill = value # 塗り色:相関係数の値 )) + geom_tile(color = "white", size = 0.5) + # タイル描画、白い境界線 geom_text(aes(label = round(value, 2)), color = "white", size = 4) + # 数値ラベル追加 scale_fill_gradient2( # 3色グラデーション(負-中央-正) low = "#ff1493", mid = "black", high = "#00ffff", midpoint = 0, limit = c(-1, 1), name = "相関係数" ) + theme_minimal() + theme( axis.text.x = element_text(angle = 45, hjust = 1, color = "white"), axis.text.y = element_text(color = "white"), plot.background = element_rect(fill = "gray10"), panel.background = element_rect(fill = "gray10") ) + labs( title = "変数間相関ヒートマップ", subtitle = "mtcarsデータセット主要変数", x = "", y = "" ) + coord_fixed()

📈 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( # Y軸のフォーマット設定 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( # Y軸のフォーマット設定 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" )

🎯 レーダーチャート:多次元パフォーマンス比較

radar_chart_example.R
# レーダーチャート(極座標系)の作成 # レーダーチャート = 複数の指標を円形に配置して比較するグラフ library(ggplot2) # グラフ作成 library(dplyr) # データ操作 # 従業員スキル評価データ(1-10点評価) skill_data <- data.frame( skill = c("プログラミング", "データ分析", "コミュニケーション", "プロジェクト管理", "創造性", "問題解決"), employee_A = c(9, 7, 6, 4, 8, 9), employee_B = c(6, 9, 8, 9, 5, 7), employee_C = c(7, 5, 9, 8, 9, 6) ) # データをlong形式に変換 skill_long <- skill_data %>% tidyr::pivot_longer(cols = starts_with("employee"), names_to = "employee", values_to = "score") %>% mutate(employee = gsub("employee_", "従業員", employee)) # レーダーチャートの作成 # group=employee で従業員別に線を描画 radar_plot <- ggplot(skill_long, aes( x = skill, # X軸:スキル名(円周上に配置) y = score, # Y軸:スコア(中心からの距離) color = employee, # 線の色:従業員別 group = employee # グループ化:従業員別に図形を描画 )) + geom_polygon(aes(fill = employee), alpha = 0.2) + # 塗りつぶしエリア geom_point(size = 3) + # データポイント geom_line(size = 1.2) + # 線で結ぶ scale_y_continuous(limits = c(0, 10), breaks = seq(0, 10, 2)) + scale_color_manual(values = c("#00ffff", "#ff1493", "#39ff14")) + scale_fill_manual(values = c("#00ffff", "#ff1493", "#39ff14")) + coord_polar() + # 極座標系に変換(通常のXY軸→円形レーダー) theme_minimal() + theme( plot.background = element_rect(fill = "gray10"), panel.background = element_rect(fill = "gray10"), axis.text.x = element_text(color = "white", size = 10), axis.text.y = element_text(color = "gray70"), panel.grid = element_line(color = "gray30") ) + labs( title = "従業員スキル評価レーダーチャート", subtitle = "6つの主要スキル領域での比較", color = "従業員", fill = "従業員" )

📊 積み上げ棒グラフ:構成比の可視化

stacked_bar_example.R
# 売上構成比を表す積み上げ棒グラフ library(ggplot2) library(dplyr) # 四半期売上データ sales_composition <- data.frame( quarter = rep(c("Q1", "Q2", "Q3", "Q4"), each = 3), product = rep(c("スマートフォン", "タブレット", "PC"), 4), sales = c(45, 25, 30, # Q1 50, 28, 22, # Q2 48, 32, 20, # Q3 55, 30, 15) # Q4 ) # 積み上げ棒グラフ(絶対値)- デフォルトで積み上げ表示 stacked_absolute <- ggplot(sales_composition, aes( x = quarter, # X軸:四半期 y = sales, # Y軸:売上額 fill = product # 塗り色:製品別(積み上げの層を作る) )) + geom_col(alpha = 0.8, width = 0.7) + # 棒グラフ、透明度0.8、幅0.7 geom_text(aes(label = paste0(sales, "万円")), # ラベル追加 position = position_stack(vjust = 0.5), color = "white", size = 3) + # 中央配置 scale_fill_manual( values = c("スマートフォン" = "#00ffff", "タブレット" = "#ff6600", "PC" = "#39ff14") ) + labs( title = "四半期別売上構成(絶対値)", x = "四半期", y = "売上(万円)", fill = "製品" ) + theme_dark() # 積み上げ棒グラフ(比率)- position="fill"で100%表示 stacked_percentage <- ggplot(sales_composition, aes( x = quarter, # X軸:四半期 y = sales, # Y軸:売上額 fill = product # 塗り色:製品別 )) + geom_col(position = "fill", alpha = 0.8, width = 0.7) + # "fill"で比率表示 scale_y_continuous(labels = scales::percent) + # Y軸を%表示に変換 scale_fill_manual( values = c("スマートフォン" = "#00ffff", "タブレット" = "#ff6600", "PC" = "#39ff14") ) + labs( title = "四半期別売上構成(比率)", x = "四半期", y = "構成比", fill = "製品" ) + theme_dark() # 2つのプロットを並べて表示 library(gridExtra) grid.arrange(stacked_absolute, stacked_percentage, ncol = 2)

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

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

📊 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()

高度な可視化テクニック

🌟 複合グラフ:複数の情報を1つのプロットに

composite_plot_example.R
# 売上と利益率の複合グラフ # 複合グラフ = 異なるスケールの指標を1つのプロットに組み合わせ library(ggplot2) # グラフ作成 library(dplyr) # データ操作 # ビジネスデータの作成(月別トレンド) business_monthly <- data.frame( month = factor(month.abb, levels = month.abb), sales = c(120, 135, 158, 142, 168, 195, 210, 198, 185, 172, 165, 148), profit_rate = c(12.5, 14.2, 16.8, 15.1, 18.3, 22.1, 25.4, 23.8, 21.2, 19.6, 17.8, 16.3) ) # 複合グラフの作成(レイヤーを重ねる) composite_plot <- ggplot(business_monthly, aes(x = month)) + # レイヤー1: 棒グラフ(売上額) geom_col(aes(y = sales), fill = "#00ffff", alpha = 0.6, width = 0.7) + # レイヤー2: 線グラフ(利益率)- スケール調整が重要 geom_line(aes(y = profit_rate * 8, group = 1), color = "#ff1493", size = 2) + # *8でスケール調整 geom_point(aes(y = profit_rate * 8), color = "#ff1493", size = 4) + # ポイント追加 # 2軸設定:異なる単位の数値を2軸で表示 scale_y_continuous( # 主軸(左側Y軸)の設定 name = "売上(万円)", # 左Y軸ラベル sec.axis = sec_axis(~./8, name = "利益率(%)") # 右Y軸:/8で元のスケールに戻す ) + labs( title = "月別売上と利益率の推移", subtitle = "棒グラフ(売上)+ 線グラフ(利益率)", x = "月" ) + theme_dark() + theme( # 視覚的な調整 axis.title.y = element_text(color = "#00ffff"), # 左Y軸ラベル色 axis.title.y.right = element_text(color = "#ff1493"), # 右Y軸ラベル色 axis.text.x = element_text(angle = 45, hjust = 1) # X軸ラベルの回転 )

🎬 アニメーション:時間軸での変化

animated_plot_example.R
# gganimate を使ったアニメーション library(ggplot2) library(gganimate) # install.packages("gganimate") library(dplyr) # 時系列データの作成 company_growth <- expand_grid( company = c("Apple", "Google", "Microsoft", "Amazon", "Meta"), year = 2018:2023 ) %>% mutate( revenue = case_when( company == "Apple" ~ 265 + (year - 2018) * 45 + rnorm(1, 0, 10), company == "Google" ~ 136 + (year - 2018) * 35 + rnorm(1, 0, 8), company == "Microsoft" ~ 110 + (year - 2018) * 40 + rnorm(1, 0, 12), company == "Amazon" ~ 232 + (year - 2018) * 55 + rnorm(1, 0, 15), company == "Meta" ~ 55 + (year - 2018) * 25 + rnorm(1, 0, 20) ) ) # アニメーション付きバーチャートレース animated_plot <- company_growth %>% group_by(year) %>% arrange(year, -revenue) %>% mutate(rank = row_number()) %>% filter(rank <= 5) %>% ggplot(aes(rank, group = company, fill = as.factor(company), color = as.factor(company))) + geom_tile(aes(y = revenue/2, height = revenue, width = 0.9), alpha = 0.8, color = NA) + geom_text(aes(y = 0, label = paste(company, " ")), vjust = 0.2, hjust = 1, size = 5) + geom_text(aes(y = revenue, label = paste0(" $", round(revenue), "B")), hjust = 0, size = 4) + coord_flip(clip = "off", expand = FALSE) + scale_y_continuous(labels = scales::comma) + scale_x_reverse() + guides(color = FALSE, fill = FALSE) + theme_minimal() + theme( plot.title = element_text(hjust = 0, size = 22), axis.ticks.y = element_blank(), axis.text.y = element_blank(), plot.margin = margin(1,1,1,4, "cm") ) + transition_states(year, transition_length = 4, state_length = 1) + view_follow(fixed_x = TRUE) + labs(title = "Tech企業売上ランキング推移: {closest_state}年", subtitle = "売上高(十億ドル)", caption = "データ: 公開財務諸表") # アニメーションの実行 # animate(animated_plot, width = 1200, height = 1000, fps = 25, duration = 10)

🎯 擬似3D効果:奥行きのある表現

pseudo_3d_example.R
# 等高線と影を使った3D風プロット library(ggplot2) library(dplyr) # 3Dデータの作成(数学関数) create_3d_data <- function() { x <- seq(-3, 3, length.out = 50) y <- seq(-3, 3, length.out = 50) grid <- expand_grid(x = x, y = y) grid$z <- with(grid, sin(sqrt(x^2 + y^2)) * exp(-0.1 * (x^2 + y^2))) return(grid) } surface_data <- create_3d_data() # 等高線プロット contour_plot <- ggplot(surface_data, aes(x = x, y = y, z = z)) + geom_contour_filled(alpha = 0.8, bins = 15) + geom_contour(color = "white", alpha = 0.6, bins = 15) + scale_fill_viridis_d(option = "plasma", direction = -1) + labs( title = "3D数学関数の可視化", subtitle = "z = sin(√(x² + y²)) × e^(-0.1(x² + y²))", x = "X軸", y = "Y軸", fill = "高度" ) + theme_dark() + theme( plot.background = element_rect(fill = "black"), panel.grid = element_blank(), legend.position = "bottom" ) + coord_equal()

ビジネス実用グラフ集

📊 ダッシュボード:KPI可視化パネル

business_dashboard.R
# ビジネスダッシュボードの作成 library(ggplot2) library(gridExtra) library(dplyr) # KPIデータの作成 kpi_data <- list( # 売上推移 sales_trend = data.frame( date = seq(as.Date("2023-01-01"), as.Date("2023-12-31"), by = "month"), sales = c(850, 920, 1100, 980, 1250, 1400, 1600, 1450, 1200, 1100, 1350, 1500), target = 1200 ), # 地域別売上 regional_sales = data.frame( region = c("東京", "大阪", "名古屋", "福岡", "札幌"), sales = c(3500, 2800, 1900, 1400, 1200), growth = c(15.2, 8.7, 22.1, -3.4, 12.8) ) ) # プロット1: 売上推移 p1 <- ggplot(kpi_data$sales_trend, aes(x = date, y = sales)) + geom_line(color = "#00ffff", size = 2) + geom_point(color = "#00ffff", size = 3) + geom_hline(yintercept = 1200, color = "#ff1493", linetype = "dashed", size = 1) + geom_area(alpha = 0.3, fill = "#00ffff") + annotate("text", x = as.Date("2023-10-01"), y = 1220, label = "目標ライン", color = "#ff1493") + labs(title = "月別売上推移", x = "月", y = "売上(万円)") + theme_minimal() + theme(plot.title = element_text(size = 14, hjust = 0.5)) # プロット2: 地域別売上 p2 <- ggplot(kpi_data$regional_sales, aes(x = reorder(region, sales), y = sales)) + geom_col(fill = "#39ff14", alpha = 0.8) + geom_text(aes(label = scales::comma(sales)), hjust = -0.1, color = "black") + coord_flip() + labs(title = "地域別売上", x = "地域", y = "売上(万円)") + theme_minimal() + theme(plot.title = element_text(size = 14, hjust = 0.5)) # プロット3: 成長率 p3 <- ggplot(kpi_data$regional_sales, aes(x = region, y = growth)) + geom_col(aes(fill = growth > 0), alpha = 0.8) + scale_fill_manual(values = c("TRUE" = "#39ff14", "FALSE" = "#ff1493")) + geom_hline(yintercept = 0, color = "white") + geom_text(aes(label = paste0(growth, "%")), vjust = ifelse(kpi_data$regional_sales$growth > 0, -0.5, 1.2)) + labs(title = "地域別成長率", x = "地域", y = "成長率 (%)") + theme_minimal() + theme(legend.position = "none", plot.title = element_text(size = 14, hjust = 0.5)) # ダッシュボード作成 grid.arrange(p1, p2, p3, ncol = 2, nrow = 2, top = textGrob("📊 ビジネスKPIダッシュボード 2023", gp = gpar(fontsize = 18, fontface = "bold")))

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

グラフの見た目は、データの理解と信頼性に大きく影響します。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) ), # 凡例 legend.position = "bottom", legend.background = element_rect(fill = "white", color = NA), legend.key = element_blank() ) } # データサイエンス向けテーマ theme_data_science <- function(base_size = 11) { theme_minimal(base_size = base_size) + theme( # 背景 plot.background = element_rect(fill = "#0e1117", color = NA), panel.background = element_rect(fill = "#0e1117", color = NA), # テキスト text = element_text(color = "#c9d1d9"), axis.text = element_text(color = "#8b949e"), # グリッド panel.grid.major = element_line(color = "#21262d", size = 0.5), panel.grid.minor = element_blank(), # タイトル plot.title = element_text( color = "#f0f6fc", size = rel(1.3), face = "bold", margin = margin(b = 15) ) ) } # テーマの使用例 example_plot <- ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) + geom_point(size = 3, alpha = 0.8) + geom_smooth(method = "lm", se = FALSE) + scale_color_manual(values = c("#ff7b7b", "#7bc7ff", "#7bff7b")) + labs( title = "カスタムテーマの適用例", subtitle = "企業ブランド vs データサイエンス", x = "馬力", y = "燃費", color = "気筒数" ) + theme_data_science() # または theme_corporate() ), 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") )

📈 実践的なグラフ作成例

実際のデータを使ってggplot2でグラフを作成してみましょう。以下の例では、よく使われるグラフパターンとその出力結果を紹介します。

📊 散布図(Scatter Plot)

scatter_plot_example.R
# mtcarsデータセットを使用した散布図 library(ggplot2) # 基本的な散布図 p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(size = 3, alpha = 0.7) + labs(title = "車重と燃費の関係", x = "車重 (1000 lbs)", y = "燃費 (mpg)") + theme_minimal() # 回帰直線を追加 p2 <- p1 + geom_smooth(method = "lm", se = TRUE, color = "red") print(p2)

出力例:

車重 (1000 lbs) 燃費 (mpg) 車重と燃費の関係 2 3 4 5 15 20 25 30

📊 棒グラフ(Bar Chart)

bar_chart_example.R
# diamondsデータセットを使用した棒グラフ library(dplyr) # データ集計 diamond_summary <- diamonds %>% group_by(cut) %>% summarise(count = n(), .groups = 'drop') # カラフルな棒グラフ p3 <- ggplot(diamond_summary, aes(x = cut, y = count, fill = cut)) + geom_col() + scale_fill_viridis_d() + labs(title = "ダイヤモンドのカット別個数", x = "カット品質", y = "個数") + theme_minimal() + theme(legend.position = "none") print(p3)

出力例:

カット品質 個数 ダイヤモンドのカット別個数 Fair Good Very Good Premium Ideal 0 5000 10000 15000 20000

📊 ヒストグラム(Histogram)

histogram_example.R
# 正規分布データのヒストグラム set.seed(123) data <- data.frame( value = rnorm(1000, mean = 50, sd = 15) ) p4 <- ggplot(data, aes(x = value)) + geom_histogram(bins = 30, fill = "skyblue", color = "white", alpha = 0.7) + geom_density(aes(y = after_stat(density) * 1000 * 3), color = "red", size = 1) + labs(title = "データの分布(ヒストグラム + 密度曲線)", x = "値", y = "頻度") + theme_minimal() print(p4)

出力例:

頻度 データの分布(ヒストグラム + 密度曲線) 20 35 50 65 80 0 25 50 75 100

💡 グラフ作成のプロのコツ

  • 目的を明確にする:何を伝えたいかを決めてからグラフの種類を選択
  • 色の使い方:色覚多様性を考慮したカラーパレットを使用
  • 軸の設定:適切な範囲とラベルで誤解を避ける
  • レイアウト:余白と文字サイズで読みやすさを向上
  • 一貫性:シリーズ全体で統一されたスタイルを維持

📊 統計的可視化と機械学習可視化

基本的なggplot2スキルを習得したら、統計分析や機械学習の結果を効果的に可視化する技法を学びましょう。 データの背後にある統計的パターンを明確に伝える可視化は、分析結果の説得力を大幅に向上させます。

🔬 統計的推論のための可視化

統計的仮説検定や信頼区間などの概念を可視化することで、分析結果をより理解しやすく伝えることができます。

statistical_inference_plots.R
# 統計的推論の可視化 library(tidyverse) library(ggplot2) library(scales) # 1. 信頼区間の可視化 set.seed(123) sample_data <- tibble( group = rep(c("A", "B", "C"), each = 100), value = c(rnorm(100, 10, 2), rnorm(100, 12, 2.5), rnorm(100, 11, 1.8)) ) # 信頼区間付きの平均値比較 confidence_plot <- sample_data %>% group_by(group) %>% summarise( mean_val = mean(value), se = sd(value) / sqrt(n()), ci_lower = mean_val - 1.96 * se, ci_upper = mean_val + 1.96 * se, .groups = 'drop' ) %>% ggplot(aes(x = group, y = mean_val, color = group)) + geom_point(size = 4) + geom_errorbar(aes(ymin = ci_lower, ymax = ci_upper), width = 0.2, size = 1) + labs(title = "グループ間平均値の比較(95%信頼区間)", y = "平均値", x = "グループ") + theme_minimal()

🤖 機械学習結果の可視化

機械学習モデルの性能評価、特徴量の重要度、予測結果などを効果的に可視化する方法を学びます。

ml_visualization.R
# 機械学習結果の可視化 library(tidyverse) library(tidymodels) library(ggplot2) # 1. 特徴量重要度の可視化 feature_importance <- tibble( feature = c("年齢", "収入", "教育レベル", "職業", "地域", "家族構成", "趣味", "購入履歴", "ウェブ行動", "季節性"), importance = c(0.15, 0.23, 0.12, 0.08, 0.05, 0.07, 0.04, 0.18, 0.06, 0.02) ) importance_plot <- feature_importance %>% mutate(feature = fct_reorder(feature, importance)) %>% ggplot(aes(x = importance, y = feature)) + geom_col(fill = "steelblue") + geom_text(aes(label = scales::percent(importance)), hjust = -0.1) + labs(title = "機械学習モデル:特徴量重要度", x = "重要度", y = "特徴量") + theme_minimal()

🌐 高次元データの可視化

pca_visualization.R
# 主成分分析(PCA)の可視化 library(tidyverse) library(ggplot2) # 相関行列のヒートマップ correlation_data <- mtcars %>% select_if(is.numeric) %>% cor() %>% as.data.frame() %>% rownames_to_column("var1") %>% pivot_longer(-var1, names_to = "var2", values_to = "correlation") correlation_heatmap <- correlation_data %>% ggplot(aes(x = var1, y = var2, fill = correlation)) + geom_tile() + scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0) + labs(title = "変数間相関関係ヒートマップ") + theme_minimal()

💡 可視化のベストプラクティス

📊 統計的可視化の原則

  • 不確実性を明示する:信頼区間やエラーバーで統計的不確実性を表現
  • 適切なスケールを選択:対数スケールや標準化で比較しやすく
  • 色使いに意味を持たせる:カテゴリや値の大小を直感的に表現
  • ストーリーを構築する:単なる数値の羅列ではなく、洞察に導く
  • 対象者を考慮する:専門家向けか一般向けかで詳細度を調整

⚠️ よくある可視化の落とし穴

  • 誤解を招くスケール:y軸の範囲操作で印象を歪めない
  • 相関の錯覚:見かけ上の相関を因果関係と誤解させない
  • 情報過多:一つのグラフに詰め込みすぎない
  • 色覚への配慮不足:色覚多様性を考慮した色選択を
  • 統計的有意性の誤解:p-hackingや多重比較の問題を理解する

これらの統計的可視化技法をマスターすることで、データの背後にある真の洞察を効果的に伝えることができます。 美しいだけでなく、科学的に正確で意味のある可視化を心がけましょう。