相関係数付きペアプロット

地域の成長に関する 4 変数の散布図行列。対角線上に群別の密度、その上に全体と群内の相関係数を示します。

相関係数付きペアプロット

GGally::ggpairs() の Python 版です。対角線より下には変数の各ペアの散布図を群ごとに色分けして描き、対角線上には各変数の群別の密度を示し、対角線より上の対称なセルにはピアソンの r を全体(太字)と群ごとに有意性の星印付きで表示しています。この2つを比べることが要点です。群がプロットの異なる領域に位置していると、全体の相関と群内の相関は大きく異なり、符号が逆になることさえあります。

設定は Hadengue & Warin (2014, Management international) による、ブラジル、中国、インドにおける特化と(無)条件収束の研究です。データは説明のための シミュレーション であり、論文のデータや結果では ありません。86 の地域(ブラジルの 27 州、中国の 31 省、インドの 28 州)について、平均成長率、1人当たり初期所得の対数、特化指数、輸出多様化指数を用意しています。各国の内部では貧しい地域ほど速く成長しますが(条件付き収束)、全体の相関には国どうしの差が混ざります。密度は scipy.stats.gaussian_kde、相関は scipy.stats.pearsonr で求め、グリッドは単純な plt.subplots(4, 4) です。

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

pairs-plot.py · 71 行
ダウンロード GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats

# Simulated data, set in the context of Hadengue & Warin (2014) [hadengue2014]

# Simulated regions: country means differ; within a country, poorer regions grow faster
rng = np.random.default_rng(2014)
groups = ["Brazil", "China", "India"]
setup = {"Brazil": (27, 9.2, 2.5), "China": (31, 9.0, 9.0), "India": (28, 7.4, 6.0)}
parts = []
for g, (n, inc0, gr0) in setup.items():
    dev = rng.normal(0, 0.45, n)                       # region's income gap to its country mean
    spec = 0.30 - 0.12 * dev + rng.normal(0, 0.05, n)
    parts.append(pd.DataFrame({"Growth (% per yr)": gr0 - 2.2 * dev + rng.normal(0, 0.7, n),
                               "Initial income (log)": inc0 + dev,
                               "Specialisation index": spec,
                               "Export diversification": 3.4 - 4 * spec + rng.normal(0, 0.25, n),
                               "group": g}))
df = pd.concat(parts, ignore_index=True)
cols = df.columns[:4]
palette = ["#007AFF", "#FF9500", "#34C759"]
stars = lambda p: "***" if p < .001 else "**" if p < .01 else "*" if p < .05 else ""

fig, axes = plt.subplots(4, 4, figsize=(9.5, 8.6), sharex="col", layout="constrained")
lims = {c: (df[c].min() - 0.05 * np.ptp(df[c]), df[c].max() + 0.05 * np.ptp(df[c])) for c in cols}
fig.get_layout_engine().set(rect=(0, 0, 1, 0.92), w_pad=0.04, h_pad=0.04)
for i, yv in enumerate(cols):
    for j, xv in enumerate(cols):
        ax = axes[i, j]
        ax.grid(False)
        if i == j:                                       # diagonal: KDE per group
            grid = np.linspace(*lims[xv], 200)
            for s, c in zip(groups, palette):
                dens = stats.gaussian_kde(df.loc[df.group == s, xv])(grid)
                ax.fill_between(grid, dens, color=c, alpha=0.25, lw=0)
                ax.plot(grid, dens, color=c, lw=1.3)
            ax.set_yticks([])
        elif i > j:                                      # lower: scatter by group
            for s, c in zip(groups, palette):
                d = df[df.group == s]
                ax.scatter(d[xv], d[yv], s=12, color=c, alpha=0.65, lw=0)
            ax.set_ylim(lims[yv])
        else:                                            # upper: correlation coefficients
            r, p = stats.pearsonr(df[xv], df[yv])
            ax.text(0.5, 0.78, f"r = {r:.2f}{stars(p)}", ha="center", fontsize=11,
                    fontweight="semibold", transform=ax.transAxes)
            for k, (s, c) in enumerate(zip(groups, palette)):
                d = df[df.group == s]
                rs, ps = stats.pearsonr(d[xv], d[yv])
                ax.text(0.5, 0.52 - k * 0.17, f"{s}: {rs:.2f}{stars(ps)}", ha="center",
                        fontsize=9, color=c, transform=ax.transAxes)
            ax.tick_params(labelbottom=False, labelleft=False)
            for sp in ax.spines.values():
                sp.set_visible(False)
        if i < 3:
            ax.tick_params(labelbottom=False)
        if j > 0 or i == 0:
            ax.tick_params(labelleft=False)
        if i == 3:
            ax.set_xlabel(xv)
            ax.set_xlim(lims[xv])
        if j == 0:
            ax.set_ylabel(yv)

fig.text(0.01, 0.985, "Within each country, poorer regions grow faster", fontsize=13,
         fontweight="semibold", va="top")
fig.text(0.01, 0.945, f"Pearson r, overall (bold) and within country · n = {len(df)} regions "
         "(simulated) · * p<.05  ** p<.01  *** p<.001", fontsize=9.5, color="#6E6E73", va="top")
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.
  • Hadengue & Warin (2014), specialisation and convergence in Brazil, China and India. Hadengue, M., & Warin, T. (2014). Patterns of specialization and (un)conditional convergence: The cases of Brazil, China and India. Management international, 18, 123–141. https://doi.org/10.7202/1027869ar
    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). Pairs plot with correlations. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/correlation/pairs-plot/

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

相関と関連のその他のグラフ