山脊图

以相互重叠的密度曲线比较多个组的同一分布。

山脊图

山脊图(又称“joy”图)为每组绘制一条密度曲线并纵向堆叠,曲线之间略有重叠,从而在一张紧凑的图中容纳许多分布。这里每条山脊代表一个经合组织(OECD)国家,展示其经常账户余额在各年份间的分布;山脊按中位数排序,深色刻线标出中位数,颜色也编码中位数(红色 = 逆差,蓝色 = 顺差),于是长期顺差国和逆差国,以及各国波动幅度的大小,一眼即可读出。

本例的背景是 Stojkov、Warin 与 Kjosevski(2026,Acta Oeconomica)关于经合组织国家经常账户的研究。此处的数字为说明而模拟(12 个国家 × 29 年,1995–2023 年,n = 348 个国家-年份,每个国家为一个均值加上 AR(1) 噪声),并非论文的数据或结果。密度由 scipy.stats.gaussian_kde 计算;由于每一年为每个国家各提供一个值,副标题报告 Friedman 检验(scipy.stats.friedmanchisquare,以年份为区组),并以 Kendall's W 作为效应量。

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

ridgeline.py · 57 行
下载 GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import stats

# Simulated data, set in the context of Stojkov, Warin & Kjosevski (2026) [stojkov2026ca]

# Data: current-account balance (% of GDP), one column per country, one row per year
rng = np.random.default_rng(2026)
means = {"Norway": 8, "Switzerland": 7, "Netherlands": 5.5, "Germany": 4, "Korea": 3,
         "Japan": 2.5, "France": -0.5, "Canada": -1.5, "United Kingdom": -3,
         "United States": -3, "Australia": -3.5, "Greece": -6}
years, ca = np.arange(1995, 2024), {}
for country, mu in means.items():
    e = np.zeros(len(years))
    for t in range(1, len(years)):            # AR(1) swings around the country mean
        e[t] = 0.6 * e[t - 1] + rng.normal(0, 1.1 + 0.08 * abs(mu))
    ca[country] = mu + e
ca = pd.DataFrame(ca, index=years)

# Friedman test (years are blocks) + Kendall's W
chi2, p = stats.friedmanchisquare(*[ca[c] for c in ca])
W = chi2 / (len(ca) * (ca.shape[1] - 1))

medians = ca.median().sort_values(ascending=False)    # largest surplus on top
grid = np.linspace(-13, 21, 400)
cmap = sns.diverging_palette(15, 250, as_cmap=True)  # red = deficit, blue = surplus
norm = plt.matplotlib.colors.TwoSlopeNorm(0, -10, 10)

fig, ax = plt.subplots(figsize=(8, 6.4))
spacing, height = 1.0, 1.9  # vertical gap between ridges, peak height of a ridge
for i, c in enumerate(medians.index):
    base = (len(medians) - 1 - i) * spacing
    kde = stats.gaussian_kde(ca[c])
    dens = kde(grid)
    curve = base + height * dens / dens.max() * 0.6
    ax.fill_between(grid, base, curve, color=cmap(norm(medians[c])), alpha=0.9, lw=0,
                    zorder=2 * i + 1)
    ax.plot(grid, curve, color="white", lw=1.2, zorder=2 * i + 2)
    ax.axhline(base, color="#C7C7CC", lw=0.6, zorder=2 * i)
    # Dark tick at the median
    y_med = base + height * kde(medians[c])[0] / dens.max() * 0.6
    ax.plot([medians[c]] * 2, [base, y_med], color="#1D1D1F", lw=1.6, zorder=2 * i + 2)

ax.axvline(0, color="#8E8E93", lw=0.8, ls="--", zorder=0)
ax.set_yticks([(len(medians) - 1 - i) * spacing for i in range(len(medians))], medians.index)
ax.set_ylim(-0.2, (len(medians) - 1) * spacing + height * 0.6 + 0.1)
ax.set_xlim(grid[0], grid[-1])
ax.grid(axis="x"); ax.grid(axis="y", visible=False)
ax.spines["left"].set_visible(False)
ax.set_xlabel(f"Current-account balance (% of GDP), one value per year, {years[0]}–{years[-1]}")
ax.set_title("One ridge per country, sorted by its median current account (simulated)", pad=26)
ax.text(0, 1.02, f"n = {ca.size} country-years (simulated) · "
        f"Friedman χ²({ca.shape[1] - 1}) = {chi2:.0f}, p = {p:.1e}, Kendall's W = {W:.2f}"
        " · tick = median", 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.
  • Stojkov, Warin & Kjosevski (2026), current accounts of OECD countries. Stojkov, A., Warin, T., & Kjosevski, J. (2026). Beyond the balance: An intertemporal perspective on the current accounts of OECD countries. Acta Oeconomica, 76(3), 402–429. https://doi.org/10.1556/032.2026.00539
    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). Ridgeline plot. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/distributions/ridgeline/

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

更多分布图表