When you need to compare distributions across more than four or five groups, many chart types become harder to read effectively. Faceted histograms force the eye to jump between panels, box plots reduce each group to a compact summary, and violin plots can start to feel crowded as the number of groups increases.
A ridgeline plot solves this by stacking KDE curves vertically, one per group, with each row slightly offset from the one below. Every distribution shares the same x-axis. You can scan across all groups at once and comparisons between adjacent rows are immediate.
In this article, we will build ridgeline plots two ways: first from scratch in Matplotlib, then with joypy for a quicker route.
Setting Up the Dataset
We will use synthetic well log data representing porosity distributions across seven geological formations.
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
import numpy as np
from scipy.stats import gaussian_kde
np.random.seed(99)
formations = {
‘Vardan’: np.random.normal(0.32, 0.04, 120),
‘Kelvik’: np.random.normal(0.22, 0.05, 150),
‘Stenby’: np.random.normal(0.18, 0.04, 130),
‘Morvik’: np.random.normal(0.14, 0.03, 100),
‘Halvard’: np.random.beta(2, 8, 90) * 0.5, # Skewed - mixed facies
‘Torven’: np.random.normal(0.20, 0.06, 140),
‘Elgfjord’: np.random.normal(0.16, 0.03, 110),
}
# Clip to realistic porosity range
formations = {k: np.clip(v, 0, 0.5) for k, v in formations.items()}The Halvard formation uses a beta distribution to simulate a right-skewed dataset. This is a synthetic representation of a shale-dominated interval in which lower porosity values dominate, with a smaller number of higher-porosity interbeds.
Step 1: The Default: Faceted Histograms
First, we will start with separate histograms for each formation. This keeps the distributions isolated and avoids overlap, but allows us to use the same axes.
n = len(formations)
fig, axes = plt.subplots(n, 1, figsize=(8, 10))
for ax, (name, values) in zip(axes, formations.items()):
ax.hist(values, bins=20)
ax.set_ylabel(name)
plt.tight_layout()
plt.show()This works well enough as a first pass. You can see the rough centre and spread of each formation, and any obviously unusual group will still stand out as well as any outliers.
The problem is that comparison becomes hard as soon as you want to judge the distributions against one another. Your eye has to move up and down the full figure to compare one formation with the next. Shape is also harder to read once the histograms are separated into individual panels, especially if you are looking for subtler differences such as skew or multi-modality.
That is the point where a ridgeline plot becomes useful. It keeps the same one-group-per-row structure, but turns the figure into something you can scan much more quickly.
Step 2: Building the Ridgeline From Scratch
The ridgeline version keeps the same basic idea as the faceted histograms: one distribution per formation, stacked vertically. The difference is that instead of showing counts in bins, it uses a smooth density curve for each group and offsets each one slightly above the next.
That does two useful things. First, it makes the overall shape of each distribution easier to read. Second, because every curve shares the same horizontal axis, it becomes much easier to compare neighbouring formations at a glance.
The mechanics are straightforward. For each formation, we estimate a KDE over a fixed x-range, then scale it so the peak height is comparable across groups, and then add a vertical offset before filling the area under the curve.
formations_list = list(formations.keys())
n_groups = len(formations_list)
overlap = 0.8
fig, ax = plt.subplots(figsize=(10, 8))
x_range = np.linspace(0, 0.5, 300)
colours = cm.Blues(np.linspace(0.35, 0.85, n_groups))
for i, (name, colour) in enumerate(zip(formations_list, colours)):
kde = gaussian_kde(formations[name], bw_method=0.25)
y = kde(x_range)
y_norm = y / y.max()
offset = (n_groups - 1 - i) * overlap
ax.fill_between(x_range, offset, y_norm + offset,
alpha=0.8, color=colour, zorder=i)
ax.plot(x_range, y_norm + offset,
color=’white’, linewidth=1, zorder=i)
ax.text(-0.01, offset + 0.05, name,
ha=’right’, va=’bottom’,
fontsize=9, fontweight=’bold’,
fontfamily=’monospace’, color=’#2c3e50’)
plt.show()The overlap value controls how tightly the ridges sit together. Push it higher and the curves begin to visually blend into one another. Pull it back and the figure starts to behave more like a set of separated mini-plots. Somewhere in the middle usually works best.
Normalising each KDE is also worth noting. Without that step, formations with different sample sizes or density peaks can dominate the figure visually. Normalisation shifts the emphasis away from absolute density height and onto comparative shape, which is usually the more useful story in this kind of plot.
Ridgeline plots are one of three underused chart types I think every Python data practitioner should know. I’ve covered all three over on Substack, including when to reach for each one. Link at the end.
Step 3: Choosing the Right Bandwidth
The default KDE bandwidth often over-smooths the data. This matters when you want to see real structure, bimodality, clustering, or a skewed tail.
# Default bandwidth - tends to over-smooth
kde_default = gaussian_kde(formations[’Halvard’])
# Narrower bandwidth - preserves more structure
kde_narrow = gaussian_kde(formations[’Halvard’], bw_method=0.2)For the Halvard formation, the default bandwidth would flatten the right skew. A value of 0.2 to 0.3 preserves it.
Step 4: Consistent X-Axis Range
Every group must share the same x-axis range. If you allow each KDE to choose its own range automatically, the shapes may look comparable even when they are not. One formation might appear broader or more tightly clustered simply because it has been plotted over a different span of values.
That breaks the main advantage of a ridgeline plot, which is side-by-side comparison on a common scale.
In this example, porosity is clipped between 0 and 0.5, so the KDE should also be evaluated over that same fixed interval:
x_range = np.linspace(0, 0.5, 300) # Fixed range across all formationsDefining the range once and reusing it for every formation keeps the visual comparison honest. The peak positions, the spread, and the tails all sit on the same reference frame.
This is especially important when some groups have narrower distributions than others. If each curve is allowed to autoscale, a tight formation and a broad formation can end up looking more similar than they really are. Fixing the x-axis removes that distortion and lets the differences in shape speak for themselves.
Step 5: Final Polish
Once the structure of the plot is working, the last step is presentation. Ridgeline plots can become visually noisy quite quickly, especially when several curves overlap. A few small design choices make a big difference to readability.
First, the filled areas are given a slightly transparent blue gradient so the stacked layers remain distinct without feeling heavy. The white outline on each curve helps separate one ridge from the next, particularly where neighbouring distributions overlap.
The formation labels are placed directly beside each ridge rather than in a legend. This makes the chart easier to scan because the reader does not have to keep jumping back and forth between the figure and a separate key. Removing the y-axis ticks also helps, since the labels already tell us what each row represents.
Finally, most of the spines are stripped away so the emphasis stays on the distributions themselves. The only axis that really matters here is the shared porosity scale along the bottom.
fig, ax = plt.subplots(figsize=(10, 8), facecolor=’white’)
x_range = np.linspace(0, 0.5, 300)
colours = cm.Blues(np.linspace(0.35, 0.85, n_groups))
overlap = 0.8
for i, (name, colour) in enumerate(zip(formations_list, colours)):
kde = gaussian_kde(formations[name], bw_method=0.25)
y = kde(x_range)
y_norm = y / y.max()
offset = (n_groups - 1 - i) * overlap
ax.fill_between(x_range, offset, y_norm + offset,
alpha=0.85, color=colour, zorder=i)
ax.plot(x_range, y_norm + offset,
color=’white’, linewidth=1.2, zorder=i)
ax.text(-0.005, offset + 0.06, name,
ha=’right’, va=’bottom’,
fontsize=9, fontweight=’bold’,
fontfamily=’monospace’, color=’#2c3e50’)
ax.set_xlabel(’Porosity (v/v)’, fontsize=12,
fontweight=’bold’, labelpad=10)
ax.set_title(’Porosity Distribution by Formation’,
fontsize=14, fontweight=’bold’, pad=15)
ax.set_xlim(0, 0.5)
ax.set_yticks([])
for spine in [’top’, ‘right’, ‘left’]:
ax.spines[spine].set_visible(False)
ax.spines[’bottom’].set_visible(True)
ax.tick_params(axis=’x’, labelsize=10)
plt.tight_layout()
plt.savefig(’ridgeline_porosity.png’, dpi=150,
bbox_inches=’tight’, facecolor=’white’)
plt.show()The result is a chart that still carries a fair amount of information, but feels much cleaner and easier to read than the default version.
What the Ridgeline Reveals
The Halvard formation immediately stands out. Where every other formation has a roughly symmetric bell curve, Halvard has a right-skewed distribution with a long tail towards higher porosity values. In a box plot this would appear as a positively skewed distribution. In the ridgeline plot you can see exactly where that tail sits and how it relates to the main cluster.
Its also easier to see multi-modal distributions for each distribution compared to the earlier multi-histogram plot.
None of this requires reading exact values. The shapes communicate the story directly.
Using joypy
If you want the ridgeline effect without building each layer manually, joypy gives you a much quicker route. It wraps the KDE calculation, stacking, and offsetting into a single function call, which makes it useful for exploratory work or for getting to a first draft quickly.
To use it, reshape the data into a simple long-form dataframe with one column for the group labels and another for the values being plotted:
import joypy
records = []
for name, values in formations.items():
for v in values:
records.append({’Formation’: name, ‘Porosity’: v})
df = pd.DataFrame(records)
fig, axes = joypy.joyplot(
df,
by=’Formation’,
column=’Porosity’,
figsize=(10, 7),
colormap=cm.Blues,
alpha=0.8,
linecolor=’white’,
linewidth=1.2,
title=’Porosity Distribution by Formation’,
x_range=[0, 0.5]
)That is enough to get a readable ridgeline plot with far less code.
The trade-off is control. A library approach is convenient, but the from-scratch version gives you much more say over bandwidth choice, label placement, colour handling, spacing, and the overall composition of the figure. If you are exploring ideas, joypy is handy. If you are aiming for a chart you would actually publish, the manual version is usually easier to tune properly.
When to Use a Ridgeline Plot
Ridgeline plots work best when:
You have 4 to 20 groups. Fewer and a simple overlapping KDE or violin plot is cleaner. More and the labels become unreadable.
Each group has at least 50 observations. KDE is unreliable on smaller samples.
The x-axis is continuous and shared across all groups.
You want to show shape, skewness, bimodality, spread rather than just summary statistics.
Full Code
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from scipy.stats import gaussian_kde
np.random.seed(99)
formations = {
‘Vardan’: np.random.normal(0.32, 0.04, 120),
‘Kelvik’: np.random.normal(0.22, 0.05, 150),
‘Stenby’: np.random.normal(0.18, 0.04, 130),
‘Morvik’: np.random.normal(0.14, 0.03, 100),
‘Halvard’: np.random.beta(2, 8, 90) * 0.5,
‘Torven’: np.random.normal(0.20, 0.06, 140),
‘Elgfjord’: np.random.normal(0.16, 0.03, 110),
}
formations = {k: np.clip(v, 0, 0.5) for k, v in formations.items()}
formations_list = list(formations.keys())
n_groups = len(formations_list)
overlap = 0.8
fig, ax = plt.subplots(figsize=(10, 8), facecolor=’white’)
x_range = np.linspace(0, 0.5, 300)
colours = cm.Blues(np.linspace(0.35, 0.85, n_groups))
for i, (name, colour) in enumerate(zip(formations_list, colours)):
kde = gaussian_kde(formations[name], bw_method=0.25)
y = kde(x_range)
y_norm = y / y.max()
offset = (n_groups - 1 - i) * overlap
ax.fill_between(x_range, offset, y_norm + offset,
alpha=0.85, color=colour, zorder=i)
ax.plot(x_range, y_norm + offset,
color=’white’, linewidth=1.2, zorder=i)
ax.text(-0.005, offset + 0.06, name,
ha=’right’, va=’bottom’,
fontsize=9, fontweight=’bold’,
fontfamily=’monospace’, color=’#2c3e50’)
ax.set_xlabel(’Porosity (v/v)’, fontsize=12, fontweight=’bold’, labelpad=10)
ax.set_title(’Porosity Distribution by Formation’,
fontsize=14, fontweight=’bold’, pad=15)
ax.set_xlim(0, 0.5)
ax.set_yticks([])
for spine in [’top’, ‘right’, ‘left’]:
ax.spines[spine].set_visible(False)
ax.spines[’bottom’].set_visible(True)
ax.tick_params(axis=’x’, labelsize=10)
plt.tight_layout()
plt.savefig(’ridgeline_porosity.png’, dpi=150,
bbox_inches=’tight’, facecolor=’white’)
plt.show()Building a ridgeline plot from scratch gives you full control over the output, but it also raises an obvious question: what other chart types are worth adding to your toolkit? Ridgeline plots sit alongside bump charts and beeswarm plots as visualisation types that most people never reach for, even when they would tell the story far better than a histogram or a box plot. Over on Substack I’ve put together a piece covering all three, with before-and-after examples using well log data.





