Data analysis · Intermediate · 24 min
Make statistical charts with seaborn
By Padding · Updated 18 Nov 2026
Python 3.15 · seaborn 0.13.2 · matplotlib 3.11.2 · pandas 3.1.1 · uv 0.13 (checked on python:3.15-slim)
You will turn a year of generated market prices into distribution, comparison, relationship, small-multiple and correlation charts with seaborn 0.13, then finish one of them with matplotlib so it is ready to share.
On this page
matplotlib can draw any chart, but you do the statistics yourself: bin the values, compute the means, bootstrap the intervals, fit the line, lay out the panels. seaborn is a layer on top of matplotlib that does that work for you. You hand it a tidy pandas DataFrame (one row per observation, one column per variable), name the columns for x, y and colour, and it computes and draws the summary. Because every seaborn chart is a matplotlib figure underneath, you can still change anything with matplotlib when the defaults are not what you want.
In this tutorial you build a small project around one dataset: a year of weekly prices for beans, onions, rice and tomatoes in three markets in each of five cities (Accra, Dakar, Kampala, Lagos and Nairobi), converted to US dollars per kg so cities compare. The data is generated with a fixed seed, so your numbers match the ones printed here. You draw:
- distributions with
histplot,kdeplotandecdfplot - comparisons between groups with
boxplot,violinplotandpointplot, and learn what a confidence interval bar does and does not tell you - relationships with
scatterplotandregplot - small multiples with the figure-level
relplotandcatplot - a correlation heatmap with
heatmap - one finished chart, tidied with matplotlib, ready for a report
Every chart is saved as PNG (for slides, documents and messaging apps) and SVG (for the web, sharp at any size). If you share charts over WhatsApp or to readers on prepaid mobile data, the PNG is usually the smaller and safer file; the SVG suits a web page.
Step 1 · Create the project and install seaborn
Make a throwaway project folder and add the three libraries. seaborn 0.13.2 is still seaborn's latest release, so the range allows only 0.13 patches; matplotlib and pandas are held to their current minor versions so a new release cannot change your charts under you:
mkdir -p ~/seaborn-demo
cd ~/seaborn-demo
uv init --no-package --python 3.15
uv add "seaborn>=0.13.2,<0.14" "matplotlib>=3.11,<3.12" "pandas>=3.1,<3.2"seaborn pulls in NumPy as well. Every script in this tutorial imports a shared module, common.py, so the theme, the data loading and the saving live in one place:
cd ~/seaborn-demo
cat > common.py <<'PY'
"""Shared loading, theme and saving for every chart script."""
from pathlib import Path
import matplotlib
matplotlib.use("Agg") # draw to files; no window needed
import matplotlib.pyplot as plt # noqa: E402
import pandas as pd # noqa: E402
import seaborn as sns # noqa: E402
sns.set_theme(style="whitegrid", rc={"svg.fonttype": "none"}) # keep SVG text as text
def load():
return pd.read_csv("data/prices.csv")
def save(fig, name):
Path("charts").mkdir(exist_ok=True)
for ext in ("png", "svg"):
fig.savefig(f"charts/{name}.{ext}", dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"saved charts/{name}.png and charts/{name}.svg")
PYThree lines in it matter:
matplotlib.use("Agg")draws straight to files. It works on a server or in a terminal with no screen, and it must run beforepyplotis imported.sns.set_theme(style="whitegrid", ...)sets seaborn's look for every chart: a white background with light grid lines."svg.fonttype": "none"writes the text in SVG files as real text rather than drawn outlines, so it stays searchable and screen readers can read it.
Check it worked
cd ~/seaborn-demo
uv run python -c "import seaborn, matplotlib, pandas; print(seaborn.__version__, matplotlib.__version__, pandas.__version__)"It prints 0.13.2 3.11.2 3.1.1, or later patch releases of matplotlib and pandas.
Step 2 · Generate a year of market prices
Create make_prices.py. It builds the dataset row by row. Prices rise with the distance from the farms that supply each market and with the price of fuel, tomatoes follow a season, and every price carries random noise. Each city also has its own price level. The generator is seeded with 2026, so the same rows come out every time:
cd ~/seaborn-demo
cat > make_prices.py <<'PY'
"""Generate a year of weekly market prices for four staples in five cities."""
from pathlib import Path
import numpy as np
import pandas as pd
rng = np.random.default_rng(2026)
# City: (price level against the average city, typical km from the farms that supply it)
CITIES = {
"Accra": (1.15, 140),
"Dakar": (1.05, 160),
"Kampala": (0.85, 60),
"Lagos": (1.25, 190),
"Nairobi": (1.00, 110),
}
# Item: typical price in US dollars per kg
ITEMS = {"Beans": 1.70, "Onions": 0.80, "Rice": 1.40, "Tomatoes": 0.90}
MARKETS = {"Central": 0.6, "North": 1.0, "Outer": 1.5} # distance factor
WEEKS = range(1, 53)
rows = []
for city, (level, km) in CITIES.items():
fuel = 1.0 + np.cumsum(rng.normal(0.002, 0.01, len(WEEKS))) # USD per litre, drifting up
rain = rng.gamma(2.0, 15.0, len(WEEKS)) # mm in the week
for item, base in ITEMS.items():
for market, factor in MARKETS.items():
for i, week in enumerate(WEEKS):
distance = max(5.0, km * factor + rng.normal(0, 12))
season = 1 + (0.25 * np.sin(2 * np.pi * week / 52) if item == "Tomatoes" else 0)
price = (
base * level * season
* (1 + 0.0015 * distance)
* (1 + 0.4 * (fuel[i] - 1))
* rng.lognormal(0, 0.12)
)
volume = 900 / price * rng.lognormal(0, 0.25)
rows.append({
"city": city, "market": market, "item": item, "week": week,
"price_usd_per_kg": round(price, 3),
"distance_km": round(distance, 1),
"fuel_usd_per_litre": round(fuel[i], 3),
"rainfall_mm": round(rain[i], 1),
"volume_kg": round(volume),
})
df = pd.DataFrame(rows)
Path("data").mkdir(exist_ok=True)
df.to_csv("data/prices.csv", index=False)
print(f"rows: {len(df)}, columns: {df.shape[1]}")
print(df.head(3).to_string(index=False))
PY
uv run make_prices.pyThe result is a tidy table: 5 cities × 4 items × 3 markets × 52 weeks = 3,120 rows, one per price observation. This shape is what seaborn wants. If your own data has one column per city or per week, reshape it with melt first (see reshape data with pivot and melt).
Check it worked
The script prints rows: 3120, columns: 9, then three rows of beans prices from Accra's Central market, the first one 1.876 USD per kg in week 1. data/prices.csv now exists in the project folder.
Step 3 · Draw the distribution of prices three ways
A distribution chart answers "how are the values spread?". seaborn has three, and each one shows the same data with a different trade-off. Create distributions.py:
cd ~/seaborn-demo
cat > distributions.py <<'PY'
"""Three views of one distribution: histogram, density curve and ECDF."""
import matplotlib.pyplot as plt
import seaborn as sns
from common import load, save
df = load()
order = ["Onions", "Tomatoes", "Rice", "Beans"]
fig, axes = plt.subplots(1, 3, figsize=(13, 3.8), sharex=True, layout="constrained")
sns.histplot(data=df, x="price_usd_per_kg", hue="item", hue_order=order,
binwidth=0.1, element="step", ax=axes[0])
sns.kdeplot(data=df, x="price_usd_per_kg", hue="item", hue_order=order,
common_norm=False, cut=0, ax=axes[1])
sns.ecdfplot(data=df, x="price_usd_per_kg", hue="item", hue_order=order, ax=axes[2])
for ax, title in zip(axes, ["Histogram", "Density (KDE)", "ECDF"]):
ax.set_title(title)
save(fig, "distributions")
medians = df.groupby("item")["price_usd_per_kg"].median().reindex(order)
print("median price per kg:", ", ".join(f"{k} {v:.2f}" for k, v in medians.items()))
rice = df.loc[df["item"] == "Rice", "price_usd_per_kg"]
print(f"share of rice prices at or under $2.00: {(rice <= 2.00).mean():.0%}")
PY
uv run distributions.pyThings to notice:
plt.subplots(1, 3, ...)makes a figure with three panels. Each seaborn call gets one withax=. These are axes-level functions: they draw into a panel you give them, so you can mix them freely in one figure.hue="item"splits the data by item and gives each a colour and a legend entry.hue_orderfixes the order so the colours match across panels.- Histogram:
binwidth=0.1puts prices into 10-cent bins. Change the bin width and the shape changes, so pick one that means something (here, ten cents) rather than accepting the default.element="step"draws outlines so overlapping groups stay visible. - KDE (kernel density estimate): a smoothed histogram.
common_norm=Falsescales each item's curve to its own total, so a small group is not flattened by a big one.cut=0stops the curve at the lowest and highest real price; without it the curve runs past the data and can suggest prices below zero. - ECDF (empirical cumulative distribution): for every price on the x-axis, the share of observations at or below it. There are no bins or smoothing to choose, and you can read percentiles off it directly: go up from $2.00 to the rice line and across to the y-axis.
The first time matplotlib runs it may print Matplotlib is building the font cache; this may take a moment. That happens once.
Check it worked
The script prints:
saved charts/distributions.png and charts/distributions.svg
median price per kg: Onions 1.06, Tomatoes 1.18, Rice 1.86, Beans 2.27
share of rice prices at or under $2.00: 63%Open charts/distributions.png. The rice line in the ECDF panel crosses $2.00 at a height of about 0.63, the same 63% the script printed. In the histogram, beans sit furthest right, and the beans curve in the KDE panel has a long tail towards $4.
Step 4 · Compare cities with box, violin and point plots
A categorical chart compares groups. Here you compare rice prices across the five cities four ways. Create compare.py:
cd ~/seaborn-demo
cat > compare.py <<'PY'
"""Compare rice prices across cities: box, violin and two point plots."""
import matplotlib.pyplot as plt
import seaborn as sns
from common import load, save
df = load()
rice = df[df["item"] == "Rice"]
cities = sorted(rice["city"].unique())
fig, axes = plt.subplots(2, 2, figsize=(11, 7), sharey="row", layout="constrained")
sns.boxplot(data=rice, x="city", y="price_usd_per_kg", order=cities, ax=axes[0, 0])
sns.violinplot(data=rice, x="city", y="price_usd_per_kg", order=cities,
inner="quart", cut=0, ax=axes[0, 1])
sns.pointplot(data=rice, x="city", y="price_usd_per_kg", order=cities,
errorbar=("ci", 95), seed=1, linestyle="none", capsize=0.2, ax=axes[1, 0])
sns.pointplot(data=rice, x="city", y="price_usd_per_kg", order=cities,
errorbar="sd", linestyle="none", capsize=0.2, ax=axes[1, 1])
titles = ["Box plot", "Violin plot", "Mean with 95% confidence interval", "Mean with one standard deviation"]
for ax, title in zip(axes.flat, titles):
ax.set_title(title)
save(fig, "compare-cities")
stats = rice.groupby("city")["price_usd_per_kg"].agg(["count", "mean", "std"])
stats["ci_half_width"] = 1.96 * stats["std"] / stats["count"] ** 0.5
print(stats.round(3).to_string())
PY
uv run compare.pyWhat each panel shows:
- Box plot: the box spans the middle half of the prices (the 25th to 75th percentile), the line inside is the median, the whiskers reach the furthest prices within 1.5 box-lengths, and dots beyond them are drawn one by one.
- Violin plot: the KDE from the last step, mirrored, one per city.
inner="quart"draws the median and quartiles as dashed lines. It shows shape a box hides, such as two peaks. - Point plot with
errorbar=("ci", 95): a dot at the mean and a bar for the 95% confidence interval of that mean. seaborn computes the interval by bootstrapping: it resamples the 156 rice prices per city 1,000 times, takes the mean of each resample, and keeps the middle 95% of those means.seed=1makes the resampling repeatable. - Point plot with
errorbar="sd": the same means, with a bar of one standard deviation either side.
The bottom two panels look very different from the same data, and that is the point to take away. A confidence interval answers "how sure am I about the average?" and gets shorter as you collect more rows. A standard deviation answers "how far do single prices stray from the average?" and does not shrink with more data. Two cities whose CI bars do not overlap have clearly different average prices; that says nothing about whether a single shopper in one city always pays more. Always say which bar you drew, in the chart or its caption.
The script also prints the numbers behind the bars. ci_half_width is the textbook approximation, 1.96 × standard deviation ÷ √count; seaborn's bootstrapped bars come out very close to it.
Check it worked
The table has five rows in alphabetical order (Accra and Dakar come first, Nairobi last). Among them are these two:
count mean std ci_half_width
city
Kampala 156 1.332 0.160 0.025
Lagos 156 2.337 0.374 0.059In charts/compare-cities.png, Lagos's CI bar spans roughly $2.28 to $2.40 while its SD bar spans roughly $1.96 to $2.71. Kampala is lowest in every panel.
Step 5 · Show how price moves with distance
A relationship chart puts one number against another. Do rice prices rise the further a market is from the farms? Create relationships.py:
cd ~/seaborn-demo
cat > relationships.py <<'PY'
"""How rice prices move with the distance from the farms."""
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from common import load, save
df = load()
rice = df[df["item"] == "Rice"]
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5), sharey=True, layout="constrained")
sns.scatterplot(data=rice, x="distance_km", y="price_usd_per_kg", hue="city",
style="city", alpha=0.6, s=18, ax=axes[0])
sns.regplot(data=rice, x="distance_km", y="price_usd_per_kg", seed=1,
scatter_kws={"alpha": 0.25, "s": 10}, line_kws={"color": "#0b0c0e"}, ax=axes[1])
axes[0].set_title("Scatter, one colour and marker per city")
axes[1].set_title("Linear fit with 95% confidence band")
save(fig, "distance-vs-price")
slope, intercept = np.polyfit(rice["distance_km"], rice["price_usd_per_kg"], 1)
r = rice["distance_km"].corr(rice["price_usd_per_kg"])
print(f"slope: {slope * 100:.2f} USD per kg for each extra 100 km")
print(f"correlation r = {r:.2f}")
PY
uv run relationships.pyscatterplotdraws one point per row.hue="city"andstyle="city"give each city both a colour and a marker shape, so the chart still works in greyscale and for readers with colour blindness.alpha=0.6lets overlapping points show through.regplotfits a straight line by least squares and shades a 95% confidence band around it, again by bootstrapping (seed=1makes it repeatable). The band is narrow in the middle, where most of the data is, and wider at the ends.np.polyfit(..., 1)returns the same line's slope, so you can put a number on what the chart shows.
Check it worked
The script prints slope: 0.44 USD per kg for each extra 100 km and correlation r = 0.73. In charts/distance-vs-price.png, the left panel shows Kampala's points clustered at short distances and low prices and Lagos's spread out to the right, and the right panel shows one rising line. The slope pools all five cities, so part of it is "Lagos is far away and expensive" rather than "distance raises prices" inside any one city. A chart shows association; it does not prove cause.
Step 6 · Split one chart into small multiples with relplot and catplot
When one chart holds too many lines, split it into a grid of small panels that share their axes. seaborn's figure-level functions do that in one call: relplot for relationships and lines, catplot for categories, displot for distributions. They take col= and row= to choose the panels, make their own figure, and return a FacetGrid instead of drawing into an ax you pass. Create facets.py:
cd ~/seaborn-demo
cat > facets.py <<'PY'
"""Small multiples with the figure-level functions relplot and catplot."""
import seaborn as sns
from common import load, save
df = load()
lines = sns.relplot(data=df, x="week", y="price_usd_per_kg", hue="item", col="city",
col_wrap=3, kind="line", errorbar=("ci", 95), seed=1,
height=2.6, aspect=1.3)
lines.set_titles("{col_name}")
lines.set_axis_labels("Week of the year", "USD per kg")
print("relplot panels:", len(lines.axes_dict))
save(lines.figure, "weekly-prices-by-city")
boxes = sns.catplot(data=df, x="city", y="price_usd_per_kg", col="item", col_wrap=2,
kind="box", sharey=False, height=2.8, aspect=1.4)
boxes.set_titles("{col_name}")
boxes.set_axis_labels("", "USD per kg")
print("catplot panels:", len(boxes.axes_dict))
save(boxes.figure, "price-spread-by-item")
PY
uv run facets.pyrelplot(kind="line", col="city", col_wrap=3)draws one panel per city, three to a row. Each week has three prices per item (one per market), solineplotunderneath draws their mean and shades a 95% confidence band around it. The bootstrapping makes this script take several seconds.catplot(kind="box", col="item", sharey=False)draws a box plot of city prices for each item.sharey=Falsegives each panel its own y-axis, because beans and onions cost very different amounts. Leave axes shared when readers need to compare heights across panels.set_titles("{col_name}")replaces the defaultcity = Accrapanel titles with just the name.set_axis_labelslabels every panel at once.heightandaspectsize each panel, not the whole figure. To save, use the grid's.figure.
Check it worked
The script prints relplot panels: 5 and catplot panels: 4. charts/weekly-prices-by-city.png has five panels titled with the city names and one shared legend on the right; in every panel the tomato line peaks around weeks 10 to 20 and dips around weeks 35 to 45, the season the generator built in. charts/price-spread-by-item.png has four panels titled Beans, Onions, Rice and Tomatoes, each with its own y-axis scale.
Step 7 · Draw a correlation heatmap
A heatmap shows a whole table of numbers as colours. The common use is a correlation matrix: how strongly every numeric column moves with every other. Create heatmap.py:
cd ~/seaborn-demo
cat > heatmap.py <<'PY'
"""Correlation matrix of the numeric columns, for rice only."""
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from common import load, save
df = load()
cols = ["price_usd_per_kg", "distance_km", "fuel_usd_per_litre", "rainfall_mm", "volume_kg"]
corr = df.loc[df["item"] == "Rice", cols].corr()
mask = np.triu(np.ones_like(corr, dtype=bool), k=1) # hide the mirror half
fig, ax = plt.subplots(figsize=(6.5, 5.5))
sns.heatmap(corr, mask=mask, annot=True, fmt=".2f", cmap="vlag",
vmin=-1, vmax=1, center=0, square=True, linewidths=0.5, ax=ax)
ax.set_title("Correlation between rice market measures")
ax.grid(False)
save(fig, "correlation-heatmap")
print(corr.round(2).to_string())
PY
uv run heatmap.py- The correlation uses rice rows only. Pooling all four items would mix "beans cost more than onions" into every number.
cmap="vlag"is a diverging palette: blue for negative, red for positive, near-white for zero.vmin=-1, vmax=1, center=0pins the colour scale to the full range of a correlation, so a weak 0.25 never looks as strong as a 0.73.maskhides the upper triangle, which mirrors the lower one.annot=True, fmt=".2f"writes each value in its cell, so readers do not have to judge colours.ax.grid(False)removes the theme's grid lines, which would otherwise show through the hidden half.
Check it worked
The printed matrix has 0.73 where price_usd_per_kg meets distance_km, the same r as the last step, and -0.66 between price and volume_kg: dearer weeks sell less. Rainfall is close to zero against everything, because the generator never used it to set prices. In charts/correlation-heatmap.png the price and distance cell is a strong red, the price and volume cell blue, and the upper-right half is empty.
Step 8 · Finish a chart with matplotlib
seaborn's defaults are fine for exploring. A chart for other people needs a title that states the finding, readable units, an order that helps, and a note on what the bars mean. Every seaborn chart is a matplotlib figure, so you finish it with matplotlib. Create polish.py:
cd ~/seaborn-demo
cat > polish.py <<'PY'
"""Turn the rice comparison into a chart ready to share."""
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import StrMethodFormatter
from common import load, save
sns.set_theme(style="ticks", context="talk", rc={"svg.fonttype": "none"})
df = load()
rice = df[df["item"] == "Rice"]
order = rice.groupby("city")["price_usd_per_kg"].mean().sort_values().index.tolist()
top = order[-1]
top_mean = rice.loc[rice["city"] == top, "price_usd_per_kg"].mean()
fig, ax = plt.subplots(figsize=(9, 5), layout="constrained")
sns.stripplot(data=rice, y="city", x="price_usd_per_kg", order=order,
color="#9ba1ac", alpha=0.35, size=3, jitter=0.25, ax=ax)
sns.pointplot(data=rice, y="city", x="price_usd_per_kg", order=order,
errorbar=("ci", 95), seed=1, linestyle="none", color="#0b0c0e",
markers="D", markersize=7, capsize=0.15, ax=ax)
ax.xaxis.set_major_formatter(StrMethodFormatter("${x:,.2f}"))
ax.set(xlabel="Price per kg (US dollars)", ylabel="",
title="Rice costs most in " + top)
ax.annotate(f"mean ${top_mean:.2f}", xy=(top_mean, order.index(top)),
xytext=(0, 16), textcoords="offset points", ha="center", fontsize=12)
sns.despine(left=True)
fig.text(0.01, -0.03, "Generated data: 52 weeks x 3 markets per city. Bars: 95% CI of the mean.",
fontsize=10, color="#6a707b", va="top")
save(fig, "rice-prices-final")
print("cities from cheapest to dearest:", ", ".join(order))
PY
uv run polish.pyWhat changed from the exploring charts:
set_theme(style="ticks", context="talk")swaps the grid for tick marks and scales all text up for slides. The other contexts arepaper,notebook(the default) andposter.- Cities are sorted by mean price and placed on the y-axis, so the names read horizontally and the ranking reads top to bottom.
- A
stripplotof every weekly price sits behind the means in light grey, so readers see the spread and the CI bars at once. StrMethodFormatter("${x:,.2f}")formats the tick labels as dollars.- The title states the finding,
annotatelabels the top mean, anddespine(left=True)removes the chart frame that adds nothing. fig.textadds a note under the chart saying the data is generated and what the bars mean.
Check it worked
The script prints cities from cheapest to dearest: Kampala, Nairobi, Dakar, Accra, Lagos. Open charts/rice-prices-final.png: the title reads "Rice costs most in Lagos", the x-axis is labelled in dollars, Lagos sits at the bottom with mean $2.34 above its marker, and the note under the chart mentions the 95% CI. The charts/ folder now holds 14 files, a PNG and an SVG for each of the seven charts.
When you are done, remove the demo folder with rm -rf ~/seaborn-demo.
Next steps
- See small multiples, direct labels and alt text used on real data in chart the energy data with small multiples.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials