クラスター化ヒートマップ

24 本の政党綱領間の Jaccard 類似度を、樹形図と政党ファミリーのカラーバー付きで示します。

クラスター化ヒートマップ

各行・各列は 1 つの文書で、各セルはその 2 つの文書間の類似度です(濃いほど似ている)。行と列は階層的クラスタリング(距離 1 − 類似度に対する群平均法)で並べ替えられ、樹形図が併合の履歴を示します。カラーバーは既知のグループ — 行は政党ファミリー、列は選挙年 — を示すので、教師なしの樹形図がどちらのまとまりを再発見するかが一目でわかります。

設定は Sanger & Warin (2019) の Data in Brief 掲載データセット(欧州の政党綱領間の Jaccard 類似度指数)です。ここでは 1 か国の 24 本の綱領 — 6 つの政党ファミリー × 4 回の選挙 — を扱います。類似度は numpy(シード固定)でシミュレーションしたもので、同じ政党内で高く、選挙間の時間とともに低下し、同じ選挙年に共通する議題の小さな効果が加わります。データセットの値ではありません。scipy.cluster.hierarchy.linkage が樹形図を作り、seaborn.clustermap が描画し、fcluster が 6 クラスターに切って政党ファミリーとの調整ランド指数を計算します。ラベルにファミリーと年が含まれるため、カラーバーに凡例は不要です。

コードおよび図中のテキストは英語です。

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

多変量解析とクラスタリングのその他のグラフ