Ridgeline plot
Overlapping density curves to compare one distribution across many groups.

A ridgeline (or "joy") plot stacks one density curve per group, letting them overlap slightly so that many distributions fit in one compact figure. Here each ridge is one OECD country and shows how its current-account balance was spread over the years; ridges are sorted by their median, the dark tick marks it and the colour encodes it (red = deficit, blue = surplus), so persistent surplus and deficit countries, and the width of each country's swings, read at a glance.
The setting is Stojkov, Warin & Kjosevski (2026, Acta Oeconomica), on the
current accounts of OECD countries. The numbers here are simulated for
illustration (12 countries × 29 years, 1995–2023, n = 348 country-years,
each country a mean plus AR(1) noise) and are not the paper's data or
results. Densities come from scipy.stats.gaussian_kde; because every year
gives one value per country, the subtitle reports a Friedman test
(scipy.stats.friedmanchisquare, years as blocks) with Kendall's W as
effect size.
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)
Figures use the optional PyStatlas style: add plt.style.use("pystatlas.mplstyle") to match the look exactly.
Data source
- 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.
The examples illustrate statistical methods. Their numbers are simulated unless an entry says otherwise, and their titles describe what each figure shows in these simulated data — not findings of the cited papers, nor the author's position on the substantive question. For results, context and data, rely on the papers cited here.
How to cite
PyStatlas is created and maintained by Thierry Warin. If it helped your work, please cite it.
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}
}More in Distributions
Histogram with density
Histogram, kernel density and fitted normal curve, with shape statistics.
ggplot2::geom_histogram() + geom_density()Raincloud plot
Half violin, box plot and raw points per group, drawn horizontally.
ggdist::stat_halfeye() / ggrain::geom_rain()ECDF comparison
Empirical cumulative distributions of two groups, with the Kolmogorov–Smirnov gap.
ggplot2::stat_ecdf()