相関行列
ピアソン相関の下三角ヒートマップ。有意でないセル(ホルム法)には×印を付けます。

ggcorrmat() の Python 版です。相関行列は対称なので、下三角のみを描いています。各タイルはピアソンの r を示し、−1(赤)から +1(青)までの発散型スケールで色分けしています。21 個の相関を同時に検定するため、p値は ホルム法で調整 し、調整後に α = .05 で有意でないペアは灰色にして×印を付けているので、視線はそれらを自然に飛ばします。
データは statsmodels に同梱されている米国州別の犯罪統計(sm.datasets.statecrime、50州+DC)です。相関と p値は scipy.stats.pearsonr、調整は statsmodels.stats.multitest.multipletests(method="holm") で求めています。
コードおよび図中のテキストは英語です。
from itertools import combinations
import matplotlib.pyplot as plt
import numpy as np
import statsmodels.api as sm
from scipy import stats
from statsmodels.stats.multitest import multipletests
# Data: US state crime statistics (bundled with statsmodels)
df = sm.datasets.statecrime.load_pandas().data
names = {"violent": "Violent crime", "murder": "Murder", "poverty": "Poverty",
"single": "Single parents", "hs_grad": "HS graduates", "urban": "Urban", "white": "White"}
df = df[list(names)].rename(columns=names)
k = df.shape[1]
# Pearson r and Holm-adjusted p-values for every pair
pairs = list(combinations(range(k), 2))
tests = [stats.pearsonr(df.iloc[:, i], df.iloc[:, j]) for i, j in pairs]
p_adj = multipletests([t.pvalue for t in tests], method="holm")[1]
fig, ax = plt.subplots(figsize=(7.6, 6.2))
cmap, norm = plt.get_cmap("RdBu"), plt.Normalize(-1, 1)
for (i, j), t, p in zip(pairs, tests, p_adj):
row, col = j, i # lower triangle: row > column
sig = p < 0.05
ax.add_patch(plt.Rectangle((col - 0.5 + 0.03, row - 0.5 + 0.03), 0.94, 0.94,
color=cmap(norm(t.statistic)) if sig else "#F2F2F7", lw=0))
if sig:
ax.text(col, row, f"{t.statistic:.2f}", ha="center", va="center", fontsize=10.5,
color="white" if abs(t.statistic) > 0.6 else "#1D1D1F")
else:
ax.plot([col - 0.2, col + 0.2], [row - 0.28, row + 0.12], color="#AEAEB2", lw=1)
ax.plot([col - 0.2, col + 0.2], [row + 0.12, row - 0.28], color="#AEAEB2", lw=1)
ax.text(col, row + 0.3, f"{t.statistic:.2f}", ha="center", va="center", fontsize=8, color="#8E8E93")
ax.set_xlim(-0.5, k - 1.5)
ax.set_ylim(k - 0.5, 0.5)
ax.set_xticks(range(k - 1), df.columns[:-1], rotation=35, ha="right", rotation_mode="anchor")
ax.set_yticks(range(1, k), df.columns[1:])
ax.set_aspect("equal")
ax.grid(False)
for s in ax.spines.values():
s.set_visible(False)
cb = fig.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, shrink=0.7, pad=0.02,
ticks=[-1, -0.5, 0, 0.5, 1])
cb.set_label("Pearson r", color="#3A3A3C")
cb.outline.set_visible(False)
ax.set_title("Violent crime tracks single parenthood more than poverty", pad=26)
ax.text(0, 1.02, f"Pearson correlations · n = {len(df)} (50 states + DC) · "
f"× = not significant (Holm-adjusted p ≥ .05)", transform=ax.transAxes,
fontsize=9.5, color="#6E6E73")
plt.show()
図にはオプションの PyStatlas スタイル を使用しています。同じ見た目にするには plt.style.use("pystatlas.mplstyle") を追加してください。
データの出典
- US state crime and social indicators, 2009. U.S. Census Bureau. Statistical Abstract of the United States, state tables for 2009 (crime rates from the FBI Uniform Crime Reporting program). https://www.statsmodels.org/stable/datasets/generated/statecrime.html
Compiled for statsmodels (sm.datasets.statecrime); public domain. See the statsmodels page for each variable's table and footnotes.
これらの例は統計手法を説明するためのものです。図のタイトルは、この特定のデータ(多くは小規模で、古く、部分的な標本)で図が示す内容を述べたものであり、実質的な問いに対する著者の立場ではありません。解釈、背景、データの質については、ここに挙げた元の出典を参照してください。
引用方法
PyStatlas は Thierry Warin が作成・運営しています。研究や業務に役立った場合は、ぜひ引用してください。
Warin, T. (2026). Correlation matrix. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences. https://warint.github.io/pystatlas/correlation/correlation-matrix/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
howpublished = {\url{https://warint.github.io/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}相関と関連のその他のグラフ
統計量付き散布図
カリフォルニア州 303 学区における低所得世帯の児童の割合と数学の成績 — 散布図、95% 信頼帯付きの OLS 直線、周辺ヒストグラム、ピアソンの r。
ggstatsplot::ggscatterstats()相関係数付きペアプロット
学区に関する 4 変数の散布図行列。対角線上に群別の密度、その上に全体と群内の相関係数を示します。
GGally::ggpairs()クラスタリング付きコレログラム
学区に関する 13 の指標について、r に応じて大きさと色を決めた corrplot 風の円を、階層的クラスタリングの順に並べたものです。
corrplot::corrplot(order = "hclust", addrect = 3)