統計量付き散布図

国のペアにおける貿易集約度と景気循環の相関 — 散布図、95% 信頼帯付きの OLS 直線、周辺ヒストグラム、ピアソンの r。

統計量付き散布図

ggscatterstats() の Python 版です。中央のパネルには、すべての観測値と最小二乗直線、およびその 95% 信頼帯(個々の点ではなく、各 x における y の平均についての不確実性)を示しています。上と右の周辺ヒストグラムは各変数の分布の形を示します。相関係数は、この形が妥当であることを暗黙のうちに前提としています。サブタイトルには、ピアソンの r とその 95% 信頼区間、t 検定、OLS の傾き、標本サイズを示しています。

設定は Janicki, Warin & Wunnava (2009, Review of International Economics) で、貿易統合が景気循環を同調させるというマンデルの直観を検証した研究です。データは説明のための シミュレーション であり、論文のデータや結果では ありません。190 の国のペア(20 か国のすべての組み合わせ)について、二国間貿易集約度の対数と、両国のトレンド除去後の産出の相関を用意しています。回帰直線はペア間の関連を表すもので、効果を示すものではありません。検定は scipy.stats.pearsonr、直線と信頼帯は statsmodels の OLS get_prediction().conf_int() で求めています。

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

scatter-with-stats.py · 47 行
ダウンロード GitHub
import matplotlib.pyplot as plt
import numpy as np
import statsmodels.api as sm
from scipy import stats

# Simulated data, set in the context of Janicki, Warin & Wunnava (2009) [janicki2009]

# Simulated country pairs: 20 countries -> 190 pairs; cycles co-move more where trade is denser
rng = np.random.default_rng(2009)
x = rng.normal(-5.5, 1.1, 190)                        # log(bilateral trade / combined GDP)
y = np.tanh(0.35 + 0.13 * (x + 5.5) + rng.normal(0, 0.28, 190))   # business-cycle correlation
n = len(x)

# Pearson correlation with its 95% CI
res = stats.pearsonr(x, y)
ci = res.confidence_interval(0.95)

# OLS fit and 95% confidence band for the mean
fit = sm.OLS(y, sm.add_constant(x)).fit()
grid = np.linspace(x.min(), x.max(), 200)
band = fit.get_prediction(sm.add_constant(grid)).conf_int(alpha=0.05)

fig = plt.figure(figsize=(8, 6.4))
gs = fig.add_gridspec(2, 2, width_ratios=(5, 1), height_ratios=(1, 5), wspace=0.03, hspace=0.03)
ax = fig.add_subplot(gs[1, 0])
ax_top = fig.add_subplot(gs[0, 0], sharex=ax)
ax_right = fig.add_subplot(gs[1, 1], sharey=ax)

ax.scatter(x, y, s=22, color="#007AFF", alpha=0.45, lw=0)
ax.fill_between(grid, band[:, 0], band[:, 1], color="#FF9500", alpha=0.25, lw=0)
ax.plot(grid, fit.params[0] + fit.params[1] * grid, color="#FF9500", lw=2.2)
ax.set_xlabel("Bilateral trade intensity (log of trade / combined GDP)")
ax.set_ylabel("Business-cycle correlation")
ax.grid(axis="x")

# Marginal histograms
ax_top.hist(x, bins=30, color="#007AFF", alpha=0.35, edgecolor="white")
ax_right.hist(y, bins=30, color="#007AFF", alpha=0.35, edgecolor="white", orientation="horizontal")
for a in (ax_top, ax_right):
    a.axis("off")

ax_top.set_title("Pairs that trade more have more synchronised business cycles", pad=26)
p_txt = "p < .001" if res.pvalue < 0.001 else f"p = {res.pvalue:.3f}"
ax_top.text(0, 1.06, f"Pearson r = {res.statistic:.2f}, 95% CI [{ci.low:.2f}, {ci.high:.2f}], "
            f"t({n - 2}) = {fit.tvalues[1]:.1f}, {p_txt} · slope = {fit.params[1]:.2f} · n = {n} pairs (simulated)",
            transform=ax_top.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.
  • Janicki, Warin & Wunnava (2009), endogenous optimum currency areas. Janicki, H., Warin, T., & Wunnava, P. (2009). Testing Mundell's intuition of endogenous OCA theory. Review of International Economics, 17(1), 74–86. https://doi.org/10.1111/j.1467-9396.2008.00802.x
    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). Scatterplot with statistics. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/correlation/scatter-with-stats/

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

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