带聚类的相关图

12 个发展指标的 corrplot 风格圆圈图,圆圈大小和颜色由 r 决定,并按层次聚类排序。

带聚类的相关图

corrplot(method = "circle", order = "hclust") 的 Python 版本。每个圆圈的面积随 |r| 增大,颜色表示符号,因此强相关十分醒目,弱相关则逐渐淡去。变量按层次聚类(以 1 − r 为距离的完全连接法)重新排序,使正相关的变量沿对角线聚成块;方框勾勒出三个聚类,效果同 addrect = 3。

背景设定为 Dedinec、Stojkov、Warin 与 Kocarev(2026,Journal of Sustainable Development of Energy, Water and Environment Systems)关于不均衡发展轨迹的研究。数据为用于说明的模拟数据,并非论文的数据或结果:150 个国家在收入、能源、排放、健康、教育和经济结构方面的 12 项指标,由三个相关的潜在因子生成,以便呈现出块状结构。排序来自 scipy.cluster.hierarchy.linkage 和 leaves_list,方框来自 fcluster。

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

correlogram-bubble.py · 70 行
下载 GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.patches import Circle, Rectangle
from scipy.cluster.hierarchy import fcluster, leaves_list, linkage
from scipy.spatial.distance import squareform

# Simulated data, set in the context of Dedinec, Stojkov, Warin & Kocarev (2026) [dedinec2026]

# Simulated countries: 12 indicators driven by three correlated latent factors
rng = np.random.default_rng(2026)
n = 150
income = rng.normal(0, 1, n)
human = 0.35 * income + 0.94 * rng.normal(0, 1, n)
green = -0.5 * income + 0.85 * rng.normal(0, 1, n)
loads = {"GDP per head (log)": (income, .9), "Energy use per head": (income, .8),
         "CO₂ per head": (income, .75), "Urban population": (income, .65),
         "Internet users": (income, .7), "Life expectancy": (human, .85),
         "Years of schooling": (human, .8), "Electricity access": (human, .7),
         "Child survival": (human, .8), "Renewables share": (green, .8),
         "Agriculture (% GDP)": (green, .7), "Forest cover": (green, .55)}
df = pd.DataFrame({k: w * f + np.sqrt(1 - w**2) * rng.normal(0, 1, n) for k, (f, w) in loads.items()})
corr = df.corr()

# Hierarchical clustering on the distance 1 - r, then reorder the matrix
Z = linkage(squareform(1 - corr.to_numpy(), checks=False), method="complete")
order = leaves_list(Z)
corr = corr.iloc[order, order]
clusters = fcluster(Z, t=3, criterion="maxclust")[order]
k = len(corr)

fig, ax = plt.subplots(figsize=(8.4, 7.2))
cmap, norm = plt.get_cmap("RdBu"), plt.Normalize(-1, 1)
for i in range(k):
    for j in range(k):
        r = corr.iat[i, j]
        if i == j:
            continue
        ax.add_patch(Circle((j, i), radius=0.47 * np.sqrt(abs(r)), color=cmap(norm(r)), lw=0))

# Boxes around the clusters (consecutive runs along the diagonal)
start = 0
for idx in range(1, k + 1):
    if idx == k or clusters[idx] != clusters[start]:
        ax.add_patch(Rectangle((start - 0.5, start - 0.5), idx - start, idx - start,
                               fill=False, ec="#1D1D1F", lw=1.6))
        start = idx

ax.set_xticks(range(k), corr.columns, rotation=45, ha="right", rotation_mode="anchor")
ax.set_yticks(range(k), corr.index)
ax.set_xticks(np.arange(-0.5, k), minor=True)
ax.set_yticks(np.arange(-0.5, k), minor=True)
ax.grid(which="minor", color="#E5E5EA", lw=0.8)
ax.grid(which="major", visible=False)
ax.tick_params(which="minor", length=0)
ax.set_xlim(-0.5, k - 0.5)
ax.set_ylim(k - 0.5, -0.5)
ax.set_aspect("equal")
for s in ax.spines.values():
    s.set_visible(False)

cb = fig.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, shrink=0.6, pad=0.02,
                  ticks=[-1, -0.5, 0, 0.5, 1])
cb.set_label("Pearson r", color="#3A3A3C")
cb.outline.set_visible(False)
r_ge = corr.loc["GDP per head (log)", "Energy use per head"]
ax.set_title(f"Income, energy and emissions form one block (r = {r_ge:.2f}, GDP–energy)", pad=26)
ax.text(0, 1.02, f"Pearson r · n = {len(df)} countries (simulated) · complete linkage clustering on 1 − r · "
        "circle area grows with |r|", 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.
  • Dedinec, Stojkov, Warin & Kocarev (2026), the development compression trap. Dedinec, A., Stojkov, A., Warin, T., & Kocarev, L. (2026). The development compression trap: A framework for understanding uneven development trajectories. Journal of Sustainable Development of Energy, Water and Environment Systems, 15(1).
    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). Correlogram with clustering. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/correlation/correlogram-bubble/

@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}
}

更多相关与关联图表