リッジラインプロット
重なり合う密度曲線で、多数の群にわたる分布を比較します。

リッジライン(「ジョイ」)プロットは、群ごとの密度曲線を少しずつ重ねて積み上げることで、多数の分布を1枚のコンパクトな図に収めます。ここでは各リッジが OECD の1か国に対応し、その国の経常収支が年ごとにどのように分布していたかを表しています。リッジは中央値の順に並べてあり、濃い目盛りが中央値を示し、色も中央値を表す(赤=赤字、青=黒字)ため、黒字や赤字が続く国々と、各国の変動の大きさが一目で読み取れます。
舞台は Stojkov, Warin & Kjosevski(2026、Acta Oeconomica)による、OECD 諸国の経常収支に関する研究です。ここでの数値は説明のために シミュレーション したもの(12か国 × 29年、1995〜2023年、n = 348 国・年。各国は平均に AR(1) ノイズを加えたもの)であり、論文のデータや結果ではありません。密度は scipy.stats.gaussian_kde で求めています。各年が国ごとに1つの値をもつため、サブタイトルには年をブロックとしたフリードマン検定(scipy.stats.friedmanchisquare)の結果を、効果量ケンドールの W とともに示しています。
コードおよび図中のテキストは英語です。
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()
# Ridgeline plot: the R equivalent of plot.py
# Simulated data, set in the context of Stojkov, Warin & Kjosevski (2026) [stojkov2026ca]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2026)
# Data: current-account balance (% of GDP), one column per country, one row per year
means <- c(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 <- 1995:2023
ca <- sapply(means, function(mu) { # AR(1) swings around the country mean
shocks <- c(0, rnorm(length(years) - 1, 0, 1.1 + 0.08 * abs(mu)))
mu + as.numeric(stats::filter(shocks, 0.6, method = "recursive"))
})
rownames(ca) <- years
# Friedman test (years are blocks) + Kendall's W
ft <- friedman.test(ca)
chi2 <- unname(ft$statistic)
W <- chi2 / (nrow(ca) * (ncol(ca) - 1))
medians <- sort(apply(ca, 2, median), decreasing = TRUE) # largest surplus on top
spacing <- 1.0 # vertical gap between ridges
height <- 1.9 * 0.6 # peak height of a ridge
base <- setNames((length(medians) - seq_along(medians)) * spacing, names(medians))
# One density per country, scaled to the same peak height and lifted to its baseline
ridges <- do.call(rbind, lapply(names(medians), function(country) {
k <- density(ca[, country], from = -13, to = 21, n = 400)
data.frame(country = country, median = medians[[country]], x = k$x, base = base[[country]],
y = base[[country]] + height * k$y / max(k$y))
}))
ticks <- do.call(rbind, lapply(split(ridges, ridges$country), function(r)
data.frame(country = r$country[1], x = r$median[1], base = r$base[1],
y = approx(r$x, r$y, r$median[1])$y))) # top of the dark tick at the median
# Drawn from the top ridge down, so that each ridge overlaps the one above it
ridge_layers <- lapply(names(medians), function(country) list(
geom_hline(yintercept = base[[country]], colour = "#C7C7CC", linewidth = 0.3),
geom_ribbon(data = ridges[ridges$country == country, ], aes(x, ymin = base, ymax = y, fill = median),
alpha = 0.9, colour = "white", linewidth = 0.6, outline.type = "upper"),
geom_segment(data = ticks[ticks$country == country, ], aes(x = x, xend = x, y = base, yend = y),
colour = "#1D1D1F", linewidth = 0.8)))
p <- ggplot() +
geom_vline(xintercept = 0, colour = "#8E8E93", linewidth = 0.4, linetype = "dashed") +
ridge_layers +
scale_fill_gradient2(low = "#D8434E", mid = "#F2F2F2", high = "#3B7EC0", midpoint = 0,
limits = c(-10, 10), oob = scales::squish, guide = "none") + # red = deficit, blue = surplus
scale_x_continuous(limits = c(-13, 21), expand = c(0, 0)) +
scale_y_continuous(breaks = base, labels = names(base), expand = c(0, 0),
limits = c(-0.2, max(base) + height + 0.1)) +
labs(title = "One ridge per country, sorted by its median current account (simulated)",
subtitle = sprintf(paste("n = %d country-years (simulated) · Friedman χ²(%d) = %.0f, p = %.1e,",
"Kendall's W = %.2f · tick = median"),
length(ca), ncol(ca) - 1, chi2, ft$p.value, W),
x = sprintf("Current-account balance (%% of GDP), one value per year, %d–%d",
min(years), max(years)), y = NULL) +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold"),
plot.title.position = "plot",
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
axis.text.y = element_text(colour = "#1D1D1F", vjust = 0),
panel.grid.minor = element_blank(), panel.grid.major.y = element_blank(),
plot.margin = margin(8, 14, 8, 8))
print(p)
図にはオプションの 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}
}