聚类热图

24 份政党竞选纲领之间的 Jaccard 相似度,附树状图和政党家族色条。

聚类热图

每一行和每一列都是一份文档,每个单元格是两份文档之间的相似度(颜色越深越相似)。行和列按层次聚类(基于距离 1 − 相似度的平均连接法)重新排序,树状图展示合并过程。色条给出已知分组——行为政党家族,列为选举年份——从而一眼看出无监督的聚类树重新发现的是哪种分组。

背景为 Sanger 和 Warin (2019) 发表于 Data in Brief 的数据集,即欧洲政党竞选纲领之间的 Jaccard 相似度指数:此处为同一国家的 24 份纲领——六个政党家族 × 四次选举。相似度由 numpy(固定种子)模拟:同一政党内部较高,随两次选举间隔增加而下降,另加同一选举年共同议题的小幅效应。它们并非该数据集的数值。scipy.cluster.hierarchy.linkage 构建聚类树,seaborn.clustermap 绘图,fcluster 将树切成六个聚类,以计算其与政党家族之间的调整兰德指数。标签已包含家族和年份,因此色条无需图例。

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

clustered-heatmap.py · 53 行
下载 GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.cluster.hierarchy import fcluster, linkage
from scipy.spatial.distance import squareform
from sklearn.metrics import adjusted_rand_score

# Simulated data, set in the context of Sanger & Warin (2019) [sanger2019]
rng = np.random.default_rng(1945)
families = ["Social dem.", "Conservative", "Liberal", "Green", "Radical right", "Radical left"]
years = [2005, 2009, 2013, 2017]
fam = np.repeat(families, 4)
yr = np.tile(years, 6)
labels = [f"{f} {y}" for f, y in zip(fam, yr)]
# Jaccard similarity: base + same party (decaying with time gap) + same election + noise
gap = np.abs(yr[:, None] - yr[None, :]) / 4
J = 0.10 + (fam[:, None] == fam[None, :]) * (0.20 - 0.03 * gap) + (gap == 0) * 0.04
J = np.triu(J + rng.normal(0, 0.025, J.shape), 1)
J = J + J.T + np.eye(24)  # symmetric, 1 on the diagonal
S = pd.DataFrame(J, index=labels, columns=labels)

link = linkage(squareform(1 - J, checks=False), method="average")
ari = adjusted_rand_score(fam, fcluster(link, 6, "maxclust"))
fam_pal = dict(zip(families, ["#FF3B30", "#007AFF", "#FF9500", "#34C759", "#3A3A3C", "#AF52DE"]))
yr_pal = dict(zip(years, ["#E5E5EA", "#C7C7CC", "#8E8E93", "#3A3A3C"]))

with plt.rc_context({"figure.constrained_layout.use": False}):
    g = sns.clustermap(S, row_linkage=link, col_linkage=link, cmap="Blues", vmin=0.05, vmax=0.35,
                       mask=np.eye(24, dtype=bool),
                       row_colors=pd.Series(fam, index=labels, name="Family").map(fam_pal),
                       col_colors=pd.Series(yr, index=labels, name="Election").map(yr_pal),
                       xticklabels=True, yticklabels=True, figsize=(9, 10.1),
                       dendrogram_ratio=(0.13, 0.11), colors_ratio=0.025,
                       cbar_pos=(0.02, 0.875, 0.025, 0.09),
                       cbar_kws=dict(label="Jaccard", ticks=[0.05, 0.2, 0.35]),
                       tree_kws=dict(colors="#8E8E93", linewidths=0.8))

g.figure.subplots_adjust(top=0.93)                 # keep the top of the figure for the title and subtitle
g.ax_cbar.set_position((0.02, 0.823, 0.025, 0.085))  # colour bar back in the top-left corner
g.ax_heatmap.set(xlabel="", ylabel="")
g.ax_heatmap.tick_params(axis="both", length=0, labelsize=8)
g.ax_heatmap.set_xticklabels(g.ax_heatmap.get_xticklabels(), rotation=50, ha="right")
g.ax_row_colors.set_xticks([])
g.ax_col_colors.tick_params(axis="y", length=0, labelsize=8.5)
g.ax_cbar.tick_params(labelsize=8.5)
g.ax_cbar.yaxis.label.set_size(9)
g.figure.text(0.02, 0.978, "Manifestos cluster by party family rather than by election year",
              fontsize=13, fontweight="semibold", color="#1D1D1F")
g.figure.text(0.02, 0.95, f"Average linkage on 1 − Jaccard · n = {len(S)} manifestos (simulated), "
              f"6 families × 4 elections · 6-cluster cut vs family: ARI = {ari:.2f}",
              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.
  • Sanger & Warin (2019), similarity of European party manifestos. Sanger, W., & Warin, T. (2019). Dataset of Jaccard similarity indices from 1,597 European political manifestos across 27 countries (1945–2017). Data in Brief, 24, 103907. https://doi.org/10.1016/j.dib.2019.103907
    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). Clustered heatmap. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/multivariate/clustered-heatmap/

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

更多多元分析与聚类图表