Data analysis · Intermediate · 22 min
Chart the energy data with small multiples
By Padding · Updated 18 Nov 2026
Python 3.15.2 · pandas 3.1.1 · seaborn 0.13.2 · matplotlib 3.11.2 · uv 0.13 (checked on python:3.15-slim)
You will draw three charts of African electricity from your series tables, a panel per subregion on one shared scale, a slope chart of 2000 against 2024 and stacked areas of generation by source, each labelled directly, credited to OWID and Ember, saved as SVG and PNG with written alt text.
On this page
Parts 4 and 5 turned the country table into regional totals and growth rates. Those tables answer questions, but a reader skims a table and remembers a picture. This part draws three charts that carry the series' main findings, and each one answers a different question:
- Small multiples: how did generation per person move in each subregion from 2000 to 2024? One small panel per subregion, all on the same scale, so the eye compares shapes without hunting through a tangle of lines.
- A slope chart: where did each subregion start and where is it now? Two points per subregion, joined by a line.
- Stacked areas: what is the electricity made from? Generation by source for Nigeria, Kenya and South Africa.
Every chart gets the same finishing: labels on the data instead of a legend, colours that stay distinct for readers with colour blindness, a source line crediting Our World in Data and Ember, and a written description (alt text) for people who cannot see it. You save each one twice: SVG for the web, where it stays sharp at any size, and PNG for slides, documents and messaging apps.
You keep working in ~/energy-demo. This part reads clean/energy.parquet from part 2 and summary/region_year.parquet from part 4, and writes everything to a new charts/ folder. Part 8 puts these charts in the published report, so keep them.
Step 1 · Check your inputs and add the charting libraries
Start as every part does: prove the raw file is unchanged, then look at the two tables the charts will read. A chart drawn from the wrong table looks as finished as one drawn from the right one, so check first.
cd ~/energy-demo
uv run check_raw.py
cat > inspect_inputs.py <<'PY'
import pandas as pd
ry = pd.read_parquet("summary/region_year.parquet")
print("region_year rows:", len(ry), "subregions:", ry["subregion"].nunique())
print("years:", ry["year"].min(), "to", ry["year"].max())
df = pd.read_parquet("clean/energy.parquet")
print("energy rows:", len(df), "countries:", df["iso_code"].nunique())
picked = df[df["country"].isin(["Nigeria", "Kenya", "South Africa"])]
print("years for Nigeria, Kenya, South Africa:", picked.groupby("country")["year"].count().to_dict())
PY
uv run inspect_inputs.pyNow add seaborn and matplotlib. seaborn draws statistical charts on top of matplotlib; you use seaborn for the panel grid and plain matplotlib for the other two charts and the finishing touches. seaborn 0.13.2 is still its latest release, so the range below allows only 0.13 patches. matplotlib is pinned to 3.11 patch releases:
cd ~/energy-demo
uv add "seaborn>=0.13.2,<0.14" "matplotlib>=3.11,<3.12"
uv run python -c "import seaborn, matplotlib; print(seaborn.__version__, matplotlib.__version__)"Check it worked
check_raw.py prints OK for both files. inspect_inputs.py prints region_year rows: 125 subregions: 5, years: 2000 to 2024, energy rows: 1370 countries: 55, and 25 years each for Kenya, Nigeria and South Africa. The last command prints 0.13.2 3.11.2, or later patch releases of each.
Step 2 · Put the shared chart settings in one module
Three charts should look like one set. Put everything they share in chart_style.py: the colours, the source line, the text settings, a helper that saves SVG, PNG and alt text together, and a helper that stops labels from landing on top of each other.
The colours come from the Okabe-Ito palette, designed to stay distinguishable for the common kinds of colour blindness. Each subregion keeps the same colour in every chart, so a reader who learns "Western Africa is blue" in one chart can carry it to the next. Label text stays dark grey rather than taking the line colour, because orange or yellow text on white is hard for anyone to read.
cd ~/energy-demo
cat > chart_style.py <<'PY'
"""Settings shared by every chart in this project. Import it before seaborn."""
from pathlib import Path
import matplotlib
matplotlib.use("Agg") # write files only; no window is opened
import matplotlib.pyplot as plt # noqa: E402
# Okabe-Ito colours: distinct for the common forms of colour blindness.
REGION_COLOURS = {
"Northern Africa": "#E69F00",
"Western Africa": "#0072B2",
"Middle Africa": "#009E73",
"Eastern Africa": "#D55E00",
"Southern Africa": "#CC79A7",
}
SOURCE_COLOURS = {
"Coal": "#000000",
"Gas": "#D55E00",
"Oil": "#CC79A7",
"Nuclear": "#E69F00",
"Hydro": "#0072B2",
"Wind": "#56B4E9",
"Solar": "#F0E442",
"Other renewables": "#009E73",
}
TEXT = "#2a2d33"
MUTED = "#6a707b"
CONTEXT = "#d9dce1"
SOURCE_LINE = (
"Source: Our World in Data energy dataset (github.com/owid/energy-data, commit f8de88a), "
"electricity data from Ember. CC BY 4.0."
)
plt.rcParams.update({
"svg.fonttype": "none", # keep text as real text in the SVG
"font.size": 9,
"text.color": TEXT,
"axes.labelcolor": TEXT,
"axes.edgecolor": MUTED,
"xtick.color": TEXT,
"ytick.color": TEXT,
"axes.spines.top": False,
"axes.spines.right": False,
})
def add_source(fig):
"""Write the credit line under the whole figure."""
fig.text(0.01, -0.01, SOURCE_LINE, ha="left", va="top", fontsize=7, color=MUTED)
def spread_labels(ax, ys, gap=0.05):
"""Label positions (data units) at least `gap` of the axis height apart, in input order.
Call it after the axis scale and limits are set.
"""
to_axes = ax.transData + ax.transAxes.inverted()
pos = [to_axes.transform((0, y))[1] for y in ys]
order = sorted(range(len(pos)), key=pos.__getitem__)
for below, above in zip(order, order[1:]):
pos[above] = max(pos[above], pos[below] + gap)
to_data = ax.transAxes + ax.transData.inverted()
return [to_data.transform((0, p))[1] for p in pos]
def save(fig, name, alt):
"""Save the figure as SVG and PNG, with its alt text beside it."""
out = Path("charts")
out.mkdir(exist_ok=True)
for ext in ("svg", "png"):
fig.savefig(out / f"{name}.{ext}", dpi=200, bbox_inches="tight", facecolor="white")
(out / f"{name}.alt.txt").write_text(alt.strip() + "\n")
plt.close(fig)
print(f"saved charts/{name}.svg, .png and .alt.txt ({len(alt.split())} words of alt text)")
PY
uv run python -c "import chart_style; print(len(chart_style.REGION_COLOURS), len(chart_style.SOURCE_COLOURS))"Two settings deserve a word. svg.fonttype: none writes text into the SVG as text, not as drawn outlines, so the labels stay searchable and selectable, and assistive technology can read them when the SVG is inlined in the page (an SVG placed with <img> exposes only its alt attribute, which is why this part also writes alt text). The file is smaller too. Because the font is not embedded, the text renders in whatever matching font the viewer's system has, so expect small differences in letter widths. bbox_inches="tight" crops the saved image to what is drawn, including labels and the source line that sit outside the plotting area.
spread_labels works in axes fractions (0 at the bottom of the plot, 1 at the top), so the same gap works on a linear or a log scale. It sorts the labels by height, then pushes each one up until it clears the one below.
Check it worked
The last command prints 5 8: five subregion colours and eight source colours. No window opens and no error appears.
Step 3 · Draw one panel per subregion on a shared scale
Put five lines on one chart and Southern Africa, at more than 3,000 kWh per person, flattens the other four into a band at the bottom where nobody can read them. Small multiples split the lines into a grid of panels. The rule that makes them honest is that every panel shares the same axes. If each panel picked its own scale, Eastern Africa's line from 162 to 230 kWh would look as steep as Northern Africa's from 804 to 1,646, and readers would compare shapes that are not comparable.
The values still span more than an order of magnitude, so use a log scale on the shared y-axis. On a log scale, equal vertical distances mean equal percentage changes: a doubling looks the same at 100 kWh as at 1,000. Say so in the axis label, because many readers will assume a linear scale.
Each panel also gets the other four subregions as faint grey lines behind its own line. That keeps the comparison in view while the panel focuses on one subregion. Panels are ordered from highest to lowest 2024 value, and the 2024 value is written at the end of each line:
cd ~/energy-demo
cat > chart_panels.py <<'PY'
import chart_style as cs # first: sets the file-only backend and the style
import pandas as pd
import seaborn as sns
from matplotlib.ticker import FixedLocator, FuncFormatter, NullFormatter
ry = pd.read_parquet("summary/region_year.parquet").sort_values(["subregion", "year"])
latest = ry[ry["year"] == 2024].set_index("subregion")["kwh_per_person"]
order = latest.sort_values(ascending=False).index.tolist()
g = sns.relplot(
data=ry, x="year", y="kwh_per_person",
col="subregion", col_order=order, col_wrap=3,
hue="subregion", palette=cs.REGION_COLOURS, legend=False,
kind="line", estimator=None, linewidth=2,
height=2.3, aspect=1.25,
facet_kws={"sharex": True, "sharey": True},
)
g.set(yscale="log", ylim=(100, 6000), xlim=(2000, 2024), xticks=[2000, 2010, 2020])
g.set_titles("{col_name}")
g.set_axis_labels("", "kWh per person (log scale)")
for region, ax in g.axes_dict.items():
for other, part in ry.groupby("subregion"):
if other != region:
ax.plot(part["year"], part["kwh_per_person"], color=cs.CONTEXT, linewidth=1, zorder=1)
ax.annotate(f"{latest[region]:,.0f}", (2024, latest[region]), xytext=(4, 0),
textcoords="offset points", va="center", fontsize=8)
ax.yaxis.set_major_locator(FixedLocator([100, 200, 500, 1000, 2000, 5000]))
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:,.0f}"))
ax.yaxis.set_minor_formatter(NullFormatter())
g.figure.suptitle("Electricity generation per person, 2000 to 2024", x=0.01, ha="left",
fontsize=11, fontweight="bold")
g.tight_layout()
cs.add_source(g.figure)
first = ry[ry["year"] == 2000].set_index("subregion")["kwh_per_person"]
moves = "; ".join(f"{r} from {first[r]:,.0f} to {latest[r]:,.0f}" for r in order)
alt = (
"Five small line charts, one for each African subregion, showing electricity generation "
"per person from 2000 to 2024 on a shared log scale from 100 to 6,000 kWh. "
f"Values in kWh per person, 2000 to 2024: {moves}. "
"Each panel shows the other four subregions as grey lines for comparison."
)
print(alt)
cs.save(g.figure, "per-person-by-subregion", alt)
PY
uv run chart_panels.pyestimator=None tells seaborn to draw the values as they are. By default relplot averages repeated x values and adds a confidence band, which makes no sense when each subregion has exactly one value per year.
Check it worked
The script prints the alt text, which lists the panels in order: Southern Africa from 3,989 to 3,462, Northern Africa from 804 to 1,646, Middle Africa from 128 to 235, Eastern Africa from 162 to 230 and Western Africa from 132 to 217. It ends with saved charts/per-person-by-subregion.svg, .png and .alt.txt. Open the PNG: five panels in two rows, Southern Africa first, each with one coloured line over four grey ones, the y-axis ticks (100 to 5,000) on the left of each row and the same scale in every panel, and the source line under the grid.
Step 4 · Compare 2000 with 2024 in a slope chart
The panels show the path. A slope chart shows only the start and the end, which makes the overall change and any change in rank stand out. Each subregion is a line from its 2000 value to its 2024 value, labelled at both ends with its name and number, so no legend is needed.
Three subregions end within 20 kWh of each other (217, 230 and 235), and their labels would print on top of each other. spread_labels from your style module moves them apart while keeping their order:
cd ~/energy-demo
cat > chart_slope.py <<'PY'
import chart_style as cs
import matplotlib.pyplot as plt
import pandas as pd
START, END = 2000, 2024
ry = pd.read_parquet("summary/region_year.parquet")
wide = ry.pivot(index="subregion", columns="year", values="kwh_per_person")[[START, END]]
wide = wide.sort_values(END, ascending=False)
print(wide.round().astype("int64").to_string())
fig, ax = plt.subplots(figsize=(4.2, 5.2))
for region, row in wide.iterrows():
ax.plot([START, END], [row[START], row[END]], color=cs.REGION_COLOURS[region],
linewidth=2.2, marker="o", markersize=5)
ax.set_yscale("log")
ax.set_ylim(100, 6000)
ax.set_xlim(START - 0.5, END + 0.5)
ax.set_xticks([START, END])
ax.tick_params(axis="x", length=0)
ax.yaxis.set_visible(False)
for side in ("left", "top", "right"):
ax.spines[side].set_visible(False)
left = cs.spread_labels(ax, wide[START].tolist(), gap=0.04)
right = cs.spread_labels(ax, wide[END].tolist(), gap=0.04)
for (region, row), y_left, y_right in zip(wide.iterrows(), left, right):
ax.text(START - 1, y_left, f"{region} {row[START]:,.0f}", ha="right", va="center")
ax.text(END + 1, y_right, f"{row[END]:,.0f} {region}", ha="left", va="center")
ax.set_title("kWh per person, 2000 and 2024 (log scale)", loc="left", fontsize=11,
fontweight="bold", pad=12)
cs.add_source(fig)
changes = []
for region, row in wide.iterrows():
verb = "rose" if row[END] > row[START] else "fell"
changes.append(f"{region} {verb} from {row[START]:,.0f} to {row[END]:,.0f}")
ratio = wide[END].max() / wide[END].min()
alt = (
f"Slope chart of electricity generation per person in Africa's five UN subregions in {START} "
f"and {END}, on a log scale. " + "; ".join(changes) + " kWh per person. "
f"In {END} the highest subregion generated about {ratio:.0f} times as much per person as the lowest."
)
print(alt)
cs.save(fig, "per-person-2000-vs-2024", alt)
PY
uv run chart_slope.pyThe chart makes one finding hard to miss: Middle Africa started lowest in 2000 (128 kWh) and finished above Eastern and Western Africa in 2024 (235 kWh), so its line crosses both. Southern Africa is the only subregion that fell.
The slope chart hides everything between the two years, including Middle Africa's dip from 256 kWh in 2022 to 236 in 2023, which the panels show. Part 5 showed that a different start year can change a ranking. Use the two charts together, and never a slope chart on its own when the path matters.
Check it worked
The table prints five rows from Southern Africa 3989 3462 down to Western Africa 132 217. The alt text ends with about 16 times as much per person as the lowest. Open the PNG: five lines, no legend, the names and values beside the dots at both ends, and the three labels at about 220 to 235 on the right stacked neatly instead of overlapping.
Step 5 · Stack generation by source for three countries
Totals say how much electricity there is. A stacked area says what it is made from, as bands piled on each other: the top edge is the total and each band's thickness is one source. Pick three countries with different mixes: Nigeria (gas and hydro), Kenya (a fast-changing mix) and South Africa (coal).
Group the nine source columns from part 2 into eight bands, one per palette colour, by putting bioenergy with the other renewables. For Kenya that combined band is mostly geothermal, which the codebook counts as "other renewables". A missing source value means the country reports none, as part 2 found, so fill it with zero before stacking, then check that the bands still add up to the total.
The three countries differ in size by a factor of almost 20 (South Africa generated about 248 TWh in 2024, Kenya about 13), so here each panel gets its own scale. That is the opposite of the subregion panels, and it is fine because the question is now each country's mix, not which country is bigger. Say so in the title. Fossil sources sit at the bottom of the stack and renewables on top, and each band of at least 3 per cent of the 2024 total is labelled at the right edge, with a thin line to the band:
cd ~/energy-demo
cat > chart_sources.py <<'PY'
import chart_style as cs
import matplotlib.pyplot as plt
import pandas as pd
COUNTRIES = ["Nigeria", "Kenya", "South Africa"]
BANDS = {
"Coal": ["coal_twh"],
"Gas": ["gas_twh"],
"Oil": ["oil_twh"],
"Nuclear": ["nuclear_twh"],
"Hydro": ["hydro_twh"],
"Wind": ["wind_twh"],
"Solar": ["solar_twh"],
"Other renewables": ["bioenergy_twh", "other_renewable_twh"],
}
names = list(BANDS)
df = pd.read_parquet("clean/energy.parquet")
df = df[df["country"].isin(COUNTRIES)].sort_values(["country", "year"])
bands = pd.DataFrame({b: df[cols].fillna(0).sum(axis=1) for b, cols in BANDS.items()})
bands[["country", "year", "total"]] = df[["country", "year", "generation_twh"]]
gap = (bands[names].sum(axis=1) - bands["total"]).abs().max()
print(f"largest gap between bands and total: {gap:.3f} TWh")
assert gap < 0.05, "the bands do not add up to total generation"
fig, axes = plt.subplots(3, 1, figsize=(6.2, 7.5), sharex=True)
summary = []
for ax, country in zip(axes, COUNTRIES):
part = bands[bands["country"] == country]
ax.stackplot(part["year"], [part[b] for b in names],
colors=[cs.SOURCE_COLOURS[b] for b in names], linewidth=0)
ax.set_xlim(2000, 2024)
ax.set_ylim(0, part["total"].max() * 1.05)
ax.set_title(f"{country}, TWh", loc="left", fontsize=9, fontweight="bold")
last = part.iloc[-1]
values = last[names].astype(float)
middles = values.cumsum() - values / 2
shown = [b for b in names if values[b] >= 0.03 * last["total"]]
for band, y in zip(shown, cs.spread_labels(ax, [middles[b] for b in shown], gap=0.11)):
ax.annotate(f"{band} {values[band]:.1f}", xy=(2024, middles[band]), xytext=(2025.3, y),
va="center", fontsize=8, annotation_clip=False,
arrowprops={"arrowstyle": "-", "color": cs.MUTED, "linewidth": 0.6})
first = part.iloc[0]
top_first = first[names].astype(float).idxmax()
top_last = values.idxmax()
summary.append(
f"{country} grew from {first['total']:.1f} to {last['total']:.1f} TWh; its largest source "
f"was {top_first.lower()} in 2000 ({first[top_first] / first['total']:.0%}) and "
f"{top_last.lower()} in 2024 ({values[top_last] / last['total']:.0%})"
)
fig.suptitle("Electricity generation by source, 2000 to 2024\nEach panel has its own scale",
x=0.01, ha="left", fontsize=11, fontweight="bold")
fig.tight_layout()
cs.add_source(fig)
alt = (
"Three stacked area charts of electricity generation by source, 2000 to 2024, each on its own "
"scale in TWh, with fossil sources at the bottom and renewables on top. " + ". ".join(summary) + "."
)
print(alt)
cs.save(fig, "sources-three-countries", alt)
PY
uv run chart_sources.pyThe sum check is not decoration. If a source column had been renamed or dropped in an earlier part, the bands would fall short of the total and the chart would quietly understate generation. The assert stops the script before a wrong chart is saved.
Check it worked
The first line reads largest gap between bands and total: 0.000 TWh. The alt text reports that Nigeria grew from 14.7 to 37.6 TWh with gas its largest source in both years (62 then 75 per cent), Kenya from 4.3 to 13.3 TWh with oil (60 per cent) replaced by other renewables (47 per cent), and South Africa from 210.7 to 247.5 TWh with coal falling from 93 to 84 per cent. Open the PNG: three panels, one above another, Kenya's top band (other renewables, labelled Other renewables 6.2) widening sharply after about 2014, and South Africa's thin solar and wind bands appearing on top of the coal in the last ten years.
Step 6 · Read the alt text and check the files
Alt text is the chart for someone using a screen reader, or for anyone whose connection fails to load the image. The scripts generate it from the same numbers as the chart, so it cannot drift out of date when the data changes. A good description says what kind of chart it is, what is measured and on what scale, and the main values or finding. It does not describe colours or decoration.
Generated text is a draft, not the end. Read each file aloud and ask whether someone who never sees the chart would come away with the same finding. If the chart's point is a comparison ("Middle Africa overtook Eastern and Western Africa"), add that sentence by hand when you publish.
Check all nine files at once:
cd ~/energy-demo
cat > check_charts.py <<'PY'
from pathlib import Path
NAMES = ["per-person-by-subregion", "per-person-2000-vs-2024", "sources-three-countries"]
problems = 0
for name in NAMES:
svg = Path("charts", f"{name}.svg")
png = Path("charts", f"{name}.png")
alt = Path("charts", f"{name}.alt.txt")
checks = {
"svg has the source line": svg.is_file() and "Our World in Data" in svg.read_text(),
"png is a PNG": png.is_file() and png.read_bytes()[:8] == b"\x89PNG\r\n\x1a\n",
"alt text has 30+ words": alt.is_file() and len(alt.read_text().split()) >= 30,
}
failed = [label for label, ok in checks.items() if not ok]
problems += len(failed)
sizes = f"svg {svg.stat().st_size // 1024} KB, png {png.stat().st_size // 1024} KB"
print(f"{'OK ' if not failed else 'FAIL'} {name}: {sizes}", *failed)
print("problems:", problems)
raise SystemExit(1 if problems else 0)
PY
uv run check_charts.py
cat charts/per-person-2000-vs-2024.alt.txtThe sizes matter if your readers are on prepaid mobile data or older Android phones. Each PNG at 200 dpi comes to something like 100 to 160 KB, small enough to share in a messaging app. The SVGs are smaller still and stay sharp when zoomed, which suits a web page. When you put a chart on a web page, its alt text goes in the image's alt attribute.
Check it worked
check_charts.py prints three lines starting with OK, each with the SVG and PNG sizes, then problems: 0. cat prints the slope chart's description, starting Slope chart of electricity generation per person. ls charts lists nine files: an .svg, a .png and an .alt.txt for each chart.
Step 7 · Record the chart decisions in notes.md
Add the choices you made and why to the notes, so part 7 and the final report start from the same facts:
cd ~/energy-demo
cat >> notes.md <<'MD'
## Part 6: charts
- charts/ holds three charts, each as SVG, PNG (200 dpi) and .alt.txt, built by chart_panels.py,
chart_slope.py and chart_sources.py with shared settings in chart_style.py.
- Subregion panels share one log y-axis (100 to 6,000 kWh per person), so slopes compare fairly.
Grey lines show the other subregions. Panels ordered by 2024 value.
- Slope chart, 2000 against 2024: Southern Africa is the only subregion that fell (3,989 to 3,462).
Middle Africa went from lowest (128) to above Eastern and Western Africa (235). It hides the
path in between, so publish it beside the panels.
- Source mix for Nigeria, Kenya and South Africa: each panel has its own scale, stated in the title.
Bioenergy is merged into other renewables (mostly geothermal in Kenya). Bands checked to add up
to total generation.
- Colours: Okabe-Ito, one colour per subregion or source in every chart. Labels on the data, no legends.
- Every chart carries the credit: Our World in Data energy dataset, electricity data from Ember, CC BY 4.0.
- Alt text is generated from the data; review it by hand before publishing.
MD
grep -c "^- " notes.mdCheck it worked
grep -c prints a count seven higher than before you ran the command (7 if your notes had no bullet lines yet). Open notes.md and check each figure in the new section against what your scripts printed.
Next steps
- Learn seaborn's other chart types on a fresh dataset: make statistical charts with seaborn.
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