相关矩阵

下三角 Pearson 相关热图;不显著的单元格(Holm 校正)以叉号划去。

相关矩阵

ggcorrmat() 的 Python 版本。由于相关矩阵是对称的,只绘制下三角;每个色块显示 Pearson r,并以从 −1(红)到 +1(蓝)的发散色阶着色。因为同时检验了 21 个相关系数,p 值经过 Holm 校正,校正后在 α = .05 水平上不显著的变量对会变灰并打叉,视线可以直接略过。

背景设定为 Stojkov 与 Warin(2019,Data in Brief)关于蒙代尔三元悖论的四十年数据集。数据为用于说明的模拟数据,并非该数据集的数值:120 个国家的三项三元悖论指数(汇率稳定性、货币独立性、金融开放度),构造使其总和约为 2,另加四个宏观变量。相关系数和 p 值由 scipy.stats.pearsonr 计算,校正由 statsmodels.stats.multitest.multipletests(method="holm") 完成。

代码及图中文字均为英文。

correlation-matrix.py · 61 行
下载 GitHub
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()

图表使用了可选的 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}
}

更多相关与关联图表