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

ggcorrmat() の Python 版です。相関行列は対称なので、下三角のみを描いています。各タイルはピアソンの r を示し、−1(赤)から +1(青)までの発散型スケールで色分けしています。21 個の相関を同時に検定するため、p値は ホルム法で調整 し、調整後に α = .05 で有意でないペアは灰色にして×印を付けているので、視線はそれらを自然に飛ばします。
設定は Stojkov & Warin (2019, Data in Brief) による、マンデルのトリレンマに関する 40 年分のデータセットです。データは説明のための シミュレーション であり、データセットの値では ありません。120 か国について、合計がおよそ 2 になるように作ったトリレンマの3指標(為替相場の安定性、金融政策の独立性、金融開放度)と、4つのマクロ経済変数を用意しています。相関と p 値は scipy.stats.pearsonr、補正は statsmodels.stats.multitest.multipletests(method="holm") で求めています。
コードおよび図中のテキストは英語です。
from itertools import combinations
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.multitest import multipletests
# Simulated data, set in the context of Stojkov & Warin (2019) [stojkov2019trilemma]
# Simulated cross-section: 120 countries; the trilemma indices share a budget of about 2
rng = np.random.default_rng(1999)
n = 120
share = rng.dirichlet([2, 2, 2], n) # how each country "gives up" the budget
ers, mi, ka = (np.clip(1 - share + rng.normal(0, 0.08, (n, 3)), 0, 1)).T
df = pd.DataFrame({"Exch.-rate stability": ers, "Monetary independence": mi,
"Financial openness": ka,
"Reserves (% GDP)": 8 + 25 * ers + rng.normal(0, 7, n),
"Trade openness (% GDP)": 50 + 60 * ka + rng.normal(0, 25, n),
"Inflation (%)": 6 - 4 * mi + rng.gamma(2, 1.5, n),
"GDP growth (%)": 3 + rng.normal(0, 2, n)})
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("The three trilemma indices pull against each other", pad=26)
ax.text(0, 1.02, f"Pearson correlations · n = {len(df)} countries (simulated) · "
f"× = not significant (Holm-adjusted p ≥ .05)", transform=ax.transAxes,
fontsize=9.5, color="#6E6E73")
plt.show()
# Correlation matrix: the R equivalent of plot.py
# Simulated data, set in the context of Stojkov & Warin (2019) [stojkov2019trilemma]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(1999)
# Simulated cross-section: 120 countries; the trilemma indices share a budget of about 2
n <- 120
g <- matrix(rgamma(3 * n, shape = 2), n)
share <- g / rowSums(g) # Dirichlet(2, 2, 2): how each country "gives up" the budget
idx <- pmin(pmax(1 - share + matrix(rnorm(3 * n, 0, 0.08), n), 0), 1)
ers <- idx[, 1]; mi <- idx[, 2]; ka <- idx[, 3]
d <- data.frame("Exch.-rate stability" = ers, "Monetary independence" = mi,
"Financial openness" = ka,
"Reserves (% GDP)" = 8 + 25 * ers + rnorm(n, 0, 7),
"Trade openness (% GDP)" = 50 + 60 * ka + rnorm(n, 0, 25),
"Inflation (%)" = 6 - 4 * mi + rgamma(n, shape = 2, scale = 1.5),
"GDP growth (%)" = 3 + rnorm(n, 0, 2), check.names = FALSE)
vars <- names(d)
k <- length(vars)
# Pearson r and Holm-adjusted p-values for every pair (lower triangle: row after column)
pairs <- as.data.frame(t(combn(k, 2)))
names(pairs) <- c("col", "row")
tests <- mapply(function(i, j) cor.test(d[[i]], d[[j]]), pairs$col, pairs$row, SIMPLIFY = FALSE)
pairs$r <- sapply(tests, function(t) unname(t$estimate))
pairs$p_adj <- p.adjust(sapply(tests, `[[`, "p.value"), method = "holm")
pairs$sig <- pairs$p_adj < 0.05
pairs$x <- factor(vars[pairs$col], levels = vars[-k])
pairs$y <- factor(vars[pairs$row], levels = rev(vars[-1]))
sig <- pairs[pairs$sig, ]
ns <- pairs[!pairs$sig, ]
p <- ggplot(pairs, aes(x, y)) +
geom_tile(aes(fill = ifelse(sig, r, NA)), width = 0.94, height = 0.94) +
scale_fill_gradient2("Pearson r", low = "#B2182B", mid = "#F7F7F7", high = "#2166AC", midpoint = 0,
limits = c(-1, 1), breaks = seq(-1, 1, 0.5), na.value = "#F2F2F7") +
geom_text(data = sig, aes(label = sprintf("%.2f", r), colour = abs(r) > 0.6), size = 3.7,
show.legend = FALSE) +
scale_colour_manual(values = c(`TRUE` = "white", `FALSE` = "#1D1D1F")) +
# Not significant after Holm: a grey cross, with r in small print below
geom_point(data = ns, shape = 4, size = 5, colour = "#AEAEB2", stroke = 0.6,
position = position_nudge(y = 0.08)) +
geom_text(data = ns, aes(label = sprintf("%.2f", r)), size = 2.8, colour = "#8E8E93",
nudge_y = -0.3) +
coord_equal() +
labs(title = "The three trilemma indices pull against each other",
subtitle = sprintf("Pearson correlations · n = %d countries (simulated) · × = not significant (Holm-adjusted p ≥ .05)",
n),
x = NULL, y = NULL) +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold"),
plot.title.position = "plot",
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
axis.text = element_text(colour = "#1D1D1F", size = 9.5),
axis.text.x = element_text(angle = 35, hjust = 1),
panel.grid = element_blank(),
legend.title = element_text(size = 9.5, colour = "#3A3A3C"),
legend.key.height = unit(2.2, "lines"))
print(p)
図にはオプションの PyStatlas スタイル を使用しています。同じ見た目にするには plt.style.use("pystatlas.mplstyle") を追加してください。
データの出典
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - Stojkov & Warin (2019), the Mundellian trilemma dataset. Stojkov, A., & Warin, T. (2019). Navigating through the Mundellian trilemma: A dataset of four decades. Data in Brief, 27, 104677. https://doi.org/10.1016/j.dib.2019.104677
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.
これらの例は統計手法を説明するためのものです。項目に別の記載がない限り数値はシミュレーションであり、図のタイトルはこのシミュレーションデータで図が示す内容を述べたものです。引用した論文の知見でも、実質的な問いに対する著者の立場でもありません。結果、背景、データについては、ここに挙げた論文を参照してください。
引用方法
PyStatlas は Thierry Warin が作成・運営しています。研究や業務に役立った場合は、ぜひ引用してください。
Warin, T. (2026). Correlation matrix. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/correlation/correlation-matrix/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}相関と関連のその他のグラフ
統計量付き散布図
国のペアにおける貿易集約度と景気循環の相関 — 散布図、95% 信頼帯付きの OLS 直線、周辺ヒストグラム、ピアソンの r。
ggstatsplot::ggscatterstats()相関係数付きペアプロット
地域の成長に関する 4 変数の散布図行列。対角線上に群別の密度、その上に全体と群内の相関係数を示します。
GGally::ggpairs()クラスタリング付きコレログラム
12 の開発指標について、r に応じて大きさと色を決めた corrplot 風の円を、階層的クラスタリングの順に並べたものです。
corrplot::corrplot(order = "hclust", addrect = 3)