Skip to main content

Data analysis · Beginner · 22 min

Choose the right chart for your data and keep it honest

By Padding · Updated 18 Nov 2026
Python 3.15 · matplotlib 3.11.2 · NumPy 2.5.5 (checked on python:3.15-slim)

You will match five common questions to the chart that answers each one, then redraw four misleading charts in matplotlib 3.11 (a truncated bar axis, dual axes, rainbow colours and a tilted pie) as honest versions with direct labels, a colour-blind-safe palette, a source line and written alt text, saved as SVG and 2x PNG.

On this page

A chart is an answer to a question. Pick the chart before you know the question and you get a picture that looks busy and says little; pick it to fit the question and the reader sees the answer before they read a single label. Most everyday questions about data fall into five kinds, and each has a chart that suits it:

  • Which is bigger? Comparing items: bars that start at zero, or a dot plot when the differences are small.
  • How did it change? Change over time: a line chart.
  • How are the values spread? A distribution: a histogram, or a box plot when you compare several groups.
  • What share is each part? Part of a whole: a stacked bar, not a pie.
  • Do two things move together? A relationship: a scatter plot.
Five cards, each pairing a question with a chart: which is bigger with bars or a dot plot, how did it change with a line, how are values spread with a histogram or box plot, what share is each part with a stacked bar, and do two things move together with a scatter plot
Start from the question, then pick the chart

Choosing the right kind is half the job. The other half is not misleading anyone with it. In this tutorial you draw four charts the way they often turn up in slide decks and reports, each with a common fault: a bar chart whose axis starts at 80, two lines forced onto two y-axes, six lines in rainbow colours and a tilted pie. Then you redraw each one honestly in matplotlib and finish it the same way every time: a headline that states the finding, labels on the data instead of a legend, colours that people with colour blindness can tell apart, a source line, and alt text for anyone who cannot see the image.

The data is a small set of made-up figures for a fictional company with branches in five cities, typed straight into each script, so your charts match the ones described here. For distributions and relationships, which need more data than fits in a list, Make statistical charts with seaborn picks up where this leaves off.

Step 1 · Create the project and install matplotlib

Make a throwaway folder with a virtual environment and install matplotlib, pinned to the version this tutorial was written against. NumPy comes with it; pinning it too keeps a later NumPy release from changing anything under you:

Bash
mkdir -p ~/chart-choice-demo
cd ~/chart-choice-demo
python3 -m venv .venv
. .venv/bin/activate
pip install "matplotlib==3.11.2" "numpy==2.5.5"
python -c "import matplotlib; print('matplotlib', matplotlib.__version__)"

The download is roughly 30 MB with matplotlib's own dependencies. On prepaid mobile data, do it once on Wi-Fi: pip caches the files, so installing the same versions in another project later downloads nothing.

Check it worked

The last command prints matplotlib 3.11.2. Run ls ~/chart-choice-demo and you see the .venv folder.

Step 2 · Write one style file every chart shares

Honest charts are easier when the finishing touches are not left to memory. Put them in one module, chartkit.py, that every script imports. It does four things:

  • Sets the Agg backend, so matplotlib writes files without needing a screen.
  • Defines the Okabe-Ito palette: eight colours picked so that people with the common forms of colour blindness can still tell them apart. A grey (MUTED) is there for lines that give context but are not the story.
  • Adds a source line at the bottom of the figure. new_figure reserves the bottom 6 per cent of the figure for it, through the layout engine's rect setting, so it never overlaps an axis label.
  • Saves every chart twice, as SVG for the web and as PNG at 200 dpi (twice the pixel density of a 100 dpi image, so it stays sharp on phone screens), and writes the alt text next to it when you give one.
Bash
cd ~/chart-choice-demo
cat > chartkit.py <<'PY'
"""Shared settings and helpers for every chart in this project."""
from pathlib import Path

import matplotlib

matplotlib.use("Agg")  # draw to files; no screen needed
import matplotlib.pyplot as plt

# Okabe-Ito: eight colours chosen to stay distinct with the common
# forms of colour blindness.
OKABE_ITO = {
    "black": "#000000",
    "orange": "#E69F00",
    "sky_blue": "#56B4E9",
    "green": "#009E73",
    "yellow": "#F0E442",
    "blue": "#0072B2",
    "vermillion": "#D55E00",
    "purple": "#CC79A7",
}
MUTED = "#B0B0B0"  # for context lines that are not the story
INK = "#222222"

SOURCE = "Source: made-up figures for a fictional company, generated for this tutorial."
OUT = Path("charts")

plt.rcParams.update({
    "svg.fonttype": "none",      # keep text as real text in the SVG
    "font.size": 11,
    "axes.titlesize": 13,
    "axes.titleweight": "bold",
    "axes.titlelocation": "left",
    "axes.spines.top": False,
    "axes.spines.right": False,
})


def new_figure(width=8, height=4.5, **kwargs):
    """A figure with room at the bottom for the source line."""
    fig, axes = plt.subplots(figsize=(width, height), layout="constrained", **kwargs)
    fig.get_layout_engine().set(rect=(0, 0.06, 1, 0.94))
    return fig, axes


def add_source(fig, text=SOURCE):
    fig.text(0.01, 0.015, text, ha="left", va="bottom", fontsize=9, color="#555555")


def save(fig, name, alt=None):
    """Save SVG and 2x PNG, plus the alt text when the chart is for publishing."""
    OUT.mkdir(exist_ok=True)
    fig.savefig(OUT / f"{name}.svg")
    fig.savefig(OUT / f"{name}.png", dpi=200)
    if alt:
        (OUT / f"{name}.alt.txt").write_text(" ".join(alt.split()) + "\n", encoding="utf-8")
    plt.close(fig)
    print("saved", name, "with alt text" if alt else "(draft, no alt text)")
PY
. .venv/bin/activate
python -c "import chartkit, matplotlib; print(matplotlib.get_backend(), len(chartkit.OKABE_ITO), 'colours')"

svg.fonttype set to "none" keeps every word in the SVG as real text rather than drawn shapes. Screen readers, search engines and your own grep can then read the titles, and the file is smaller. The other settings drop the top and right borders, which carry no information, and put titles on the left where the eye starts.

Check it worked

The command prints Agg 8 colours (some systems print agg). chartkit.py sits next to .venv in the folder.

Step 3 · Compare items with bars that start at zero

The question: which branch has the most satisfied customers? Scores are out of 100 and every branch sits between 81 and 89. That is comparing items, so bars are the right kind of chart. The fault in the first version is the axis: it starts at 80, so Nairobi's bar is 1 point tall and Kigali's is 9, and the eye reads that as nine times better.

Two bar charts of the same two scores, Nairobi 81 and Kigali 89. With the axis starting at 80 the bar lengths are 1 to 9; with the axis starting at 0 they are 81 to 89
A bar's length is its value only when the axis starts at zero

A bar encodes its value by length, so the axis must start at zero. If the small gaps are the point, switch to a dot plot: a dot encodes its value by position alone, so you can zoom the axis in without lying. The fixed version shows both, side by side, sorted from highest to lowest, with the value printed at the end of each bar so nobody has to read the axis:

Bash
cd ~/chart-choice-demo
. .venv/bin/activate
cat > bars.py <<'PY'
"""Comparison: satisfaction score by branch."""
from chartkit import INK, OKABE_ITO, add_source, new_figure, save

scores = {"Lagos": 84, "Accra": 87, "Nairobi": 81, "Kigali": 89, "Dakar": 85}

# Before: vertical bars on an axis that starts at 80.
fig, ax = new_figure()
ax.bar(list(scores), list(scores.values()), color=OKABE_ITO["blue"])
ax.set_ylim(80, 90)
ax.set_title("Customer satisfaction by branch")
save(fig, "1-bars-before")

# After: sorted, horizontal, from zero, labelled. A dot plot beside it
# zooms in on the gaps without pretending a bar is longer than it is.
ranked = sorted(scores.items(), key=lambda item: item[1])
names = [name for name, _ in ranked]
values = [value for _, value in ranked]

fig, (bars, dots) = new_figure(width=9, height=4.5, ncols=2)
fig.suptitle("Kigali scores highest, Nairobi lowest, 8 points apart",
             x=0.01, ha="left", fontweight="bold")

bars.barh(names, values, color=OKABE_ITO["blue"])
bars.set_xlim(0, 100)
bars.set_title("Score out of 100, axis from zero", fontsize=11, fontweight="normal")
bars.bar_label(bars.containers[0], padding=3, color=INK)
bars.spines["bottom"].set_visible(False)
bars.tick_params(axis="x", labelbottom=False, bottom=False)

dots.plot(values, names, "o", color=OKABE_ITO["blue"], markersize=9)
dots.set_xlim(78, 92)
dots.grid(axis="x", color="#DDDDDD")
dots.set_axisbelow(True)
dots.set_title("Same scores, zoomed in to 78 to 92", fontsize=11, fontweight="normal")
dots.tick_params(axis="y", labelleft=False, left=False)

add_source(fig)
save(fig, "1-bars-after", alt="""
Two charts of customer satisfaction scores out of 100 at five branches in 2026.
Kigali is highest at 89, then Accra 87, Dakar 85, Lagos 84 and Nairobi lowest at 81.
Bars drawn from zero show the branches are close; a dot plot zoomed to 78 to 92 shows
the 8-point gap between Kigali and Nairobi.
""")
PY
python bars.py

Three choices here carry over to any comparison:

  • Horizontal bars give category names room. Branch names, product names or labels in French, Swahili or Amharic often run longer than English ones, and on a vertical bar chart they end up rotated or cut off.
  • Sorting by value turns "find the biggest" into "look at the top".
  • The headline states the finding ("Kigali scores highest…"), and the small title under it says what is measured and in what unit. A title like "Customer satisfaction by branch" makes the reader do the work.

Check it worked

The script prints two saved lines. Open charts/1-bars-before.png and charts/1-bars-after.png side by side. In the first, Nairobi's bar is a stub next to Kigali's. In the second, the bars are nearly the same length, each ends in its score, and the dot plot on the right shows the 8-point spread on an axis from 78 to 92. The source line sits at the bottom left without touching anything.

Step 4 · Show change over time without a second y-axis

The question: how did monthly orders and delivery time change through 2026? Change over time calls for lines. The fault in the first version is the dual axis: orders on the left, minutes on the right, each axis range picked so the two lines lie on top of each other. The match is made by the scaling, not by the data. Choose different ranges and the lines cross, diverge or run parallel, and readers take the overlap as proof that one drives the other.

The fix is to give each measure its own panel with its own honest scale, one above the other, sharing the months along the bottom. Label the first and last values on the lines so the reader gets the size of the change without reading gridlines:

Bash
cd ~/chart-choice-demo
. .venv/bin/activate
cat > time.py <<'PY'
"""Change over time: orders and delivery time, two measures in different units."""
from chartkit import INK, OKABE_ITO, add_source, new_figure, save

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
orders = [1210, 1260, 1380, 1450, 1500, 1720, 1880, 1850, 1700, 1690, 1910, 2240]
minutes = [38, 37, 39, 41, 40, 44, 47, 46, 43, 42, 45, 49]

# Before: two y-axes, each scaled so the lines sit on top of each other.
fig, ax = new_figure()
ax.plot(months, orders, color=OKABE_ITO["blue"], linewidth=2)
ax.set_ylim(1100, 2300)
ax.set_ylabel("Orders")
right = ax.twinx()
right.plot(months, minutes, color=OKABE_ITO["vermillion"], linewidth=2)
right.set_ylim(36, 50)
right.set_ylabel("Minutes")
ax.set_title("Orders and delivery time, 2026")
save(fig, "2-time-before")

# After: one panel per measure, months shared, each with its own honest scale.
fig, (top, bottom) = new_figure(height=6, nrows=2, sharex=True)
fig.suptitle("Orders nearly doubled in 2026; average delivery time rose 11 minutes",
             x=0.01, ha="left", fontweight="bold")

top.plot(months, orders, color=OKABE_ITO["blue"], linewidth=2, marker="o", markersize=4)
top.set_ylim(0, 2500)
top.set_title("Orders per month", fontsize=11, fontweight="normal")
top.annotate(f"{orders[-1]:,}", (11, orders[-1]), xytext=(6, 0),
             textcoords="offset points", va="center", color=INK)
top.annotate(f"{orders[0]:,}", (0, orders[0]), xytext=(0, -14),
             textcoords="offset points", ha="center", color=INK)

bottom.plot(months, minutes, color=OKABE_ITO["vermillion"], linewidth=2, marker="o", markersize=4)
bottom.set_ylim(0, 60)
bottom.set_title("Average delivery time, minutes", fontsize=11, fontweight="normal")
bottom.annotate(f"{minutes[-1]} min", (11, minutes[-1]), xytext=(6, 0),
                textcoords="offset points", va="center", color=INK)
bottom.annotate(f"{minutes[0]} min", (0, minutes[0]), xytext=(0, -14),
                textcoords="offset points", ha="center", color=INK)

add_source(fig)
save(fig, "2-time-after", alt="""
Two line charts sharing the months of 2026. Orders per month rose from 1,210 in
January to 2,240 in December, with a dip in September and October. Average delivery
time rose from 38 minutes to 49 minutes over the same months. The panels show both
rose; they do not show that one caused the other.
""")
PY
python time.py

sharex=True lines the two panels up month by month and prints the month names once. A line chart does not have to start at zero the way a bar chart does, because a line shows change by slope rather than by length. Both panels start at zero here anyway, so an 11-minute rise reads at its true size against a 49-minute delivery. If you do zoom a line chart in, say so in the subtitle.

If you really need one panel, convert both series to the same unit first, for example each as a percentage of its January value, and plot them on a single axis.

Check it worked

Open charts/2-time-before.png: the two lines nearly trace each other, which looks like a strong link. Open charts/2-time-after.png: orders run from 1,210 to 2,240 in the top panel and delivery time from 38 min to 49 min in the bottom panel, both rising, on scales you can read.

Step 5 · Replace rainbow colours with a highlight and direct labels

The question: which sales channel brings in the most new customers now? Six lines over eight quarters. The fault in the first version is colour: one rainbow colour per line, taken from matplotlib's jet colormap, and a legend to decode them. Rainbow colours have no natural order, several of them look alike to people with colour blindness, and some (yellow-green on white) are hard for anyone to see. The reader also has to look back and forth between legend and lines six times.

The fix has three parts:

  • Colour only the story. The headline is about two channels, so those two get strong Okabe-Ito colours and the other four go grey. Grey lines still answer "compared with what?".
  • Label lines directly at their right-hand end, with the last value, and drop the legend. The label is right where the eye finishes reading the line.
  • Do not rely on colour alone. The two story lines are also thicker and their labels are bold, so the chart still works printed in black and white.
Bash
cd ~/chart-choice-demo
. .venv/bin/activate
cat > colours.py <<'PY'
"""Many series: sign-ups by channel. Highlight the story, grey the rest."""
import matplotlib

from chartkit import MUTED, OKABE_ITO, add_source, new_figure, save

quarters = ["Q1\n2025", "Q2", "Q3", "Q4", "Q1\n2026", "Q2", "Q3", "Q4"]
x = range(len(quarters))  # positions; the labels repeat, so do not plot against them
signups = {
    "WhatsApp":   [120, 180, 260, 340, 450, 560, 690, 820],
    "Agents":     [400, 430, 450, 470, 500, 520, 540, 560],
    "Radio":      [380, 360, 350, 330, 320, 300, 290, 270],
    "Referral":   [150, 165, 180, 195, 210, 225, 240, 255],
    "Website":    [210, 200, 190, 185, 175, 165, 160, 150],
    "Billboards": [90, 85, 85, 80, 75, 70, 70, 65],
}

# Before: one rainbow colour per line and a legend to decode them.
rainbow = matplotlib.colormaps["jet"]
fig, ax = new_figure()
for i, (channel, values) in enumerate(signups.items()):
    ax.plot(x, values, color=rainbow(i / (len(signups) - 1)), linewidth=2, label=channel)
ax.legend(loc="upper left", ncols=2, frameon=False)
ax.set_xticks(x, quarters)
ax.set_title("Sign-ups by channel")
save(fig, "3-colours-before")


def spread(positions, gap):
    """Nudge label heights apart so no two are closer than gap."""
    order = sorted(range(len(positions)), key=lambda i: positions[i])
    placed = list(positions)
    for previous, current in zip(order, order[1:]):
        placed[current] = max(placed[current], placed[previous] + gap)
    return placed


# After: two colours for the two lines the title talks about, grey for context,
# and a name at the end of every line instead of a legend.
story = {"WhatsApp": OKABE_ITO["blue"], "Agents": OKABE_ITO["orange"]}
fig, ax = new_figure()
fig.suptitle("WhatsApp overtook agents as the biggest source of sign-ups in 2026",
             x=0.01, ha="left", fontweight="bold")
ax.set_title("New customers per quarter, by channel", fontsize=11, fontweight="normal")
for channel, values in signups.items():
    colour = story.get(channel, MUTED)
    ax.plot(x, values, color=colour, linewidth=3 if channel in story else 1.5,
            zorder=3 if channel in story else 2)

channels = list(signups)
label_heights = spread([signups[c][-1] for c in channels], gap=45)
for channel, height in zip(channels, label_heights):
    last = signups[channel][-1]
    ax.annotate(f"{channel} {last}", (len(quarters) - 1, height), xytext=(8, 0),
                textcoords="offset points", va="center",
                color=story.get(channel, "#666666"),
                fontweight="bold" if channel in story else "normal")
ax.set_ylim(0, 900)
ax.set_xlim(-0.3, len(quarters) - 1 + 1.6)  # room on the right for the labels
ax.spines["bottom"].set_bounds(0, len(quarters) - 1)
ax.set_xticks(x, quarters)

add_source(fig)
save(fig, "3-colours-after", alt="""
Line chart of new customers per quarter from six channels, 2025 Q1 to 2026 Q4.
WhatsApp, highlighted in blue, rose from 120 to 820 and passed agents, highlighted
in orange, in the second quarter of 2026; agents grew slowly from 400 to 560. The other four channels are grey:
radio fell from 380 to 270, website from 210 to 150, billboards from 90 to 65, and
referral rose from 150 to 255.
""")
PY
python colours.py

Two details in the code are worth knowing. The quarter labels repeat (Q2 appears in both years), and matplotlib treats repeated text labels as the same position, which tangles the lines; plotting against positions 0 to 7 and setting the labels with set_xticks avoids that. And when two lines end close together their labels collide, so spread pushes labels apart until no two are closer than 45 units; here it lifts Radio 270 just clear of Referral 255.

Check it worked

Open charts/3-colours-before.png and try to tell which line is Radio without the legend. Then open charts/3-colours-after.png: a thick blue line labelled WhatsApp 820 crosses a thick orange Agents 560 line in the second quarter of 2026, four grey lines sit below them with their names at the right, and there is no legend.

Step 6 · Show parts of a whole as stacked bars, not a pie

The question: how did the way customers pay change between 2024 and 2026? That is part of a whole, compared across two years. The fault in the first version is the tilted, exploded pie with shadows, the look a "3D pie" button in a spreadsheet gives you. Tilting a pie makes the slices at the front look bigger than the ones at the back, exploding one slice inflates it further, and comparing slices across two pies means judging angles in two places at once. Without the numbers, nobody can tell from the pies how much mobile money grew.

matplotlib has no 3D pie, so the script imitates one by squashing an ordinary pie with set_aspect(0.45). The fix is one bar per year, each adding up to 100 per cent, in the same order, with the share printed inside every segment:

Bash
cd ~/chart-choice-demo
. .venv/bin/activate
cat > parts.py <<'PY'
"""Part of a whole: how customers paid, 2024 against 2026."""
from chartkit import OKABE_ITO, add_source, new_figure, save

methods = ["Cash", "Mobile money", "Card", "Bank transfer"]
shares = {  # per cent of payments; each year adds up to 100
    "2024": [46, 30, 16, 8],
    "2026": [31, 44, 17, 8],
}
assert all(sum(row) == 100 for row in shares.values())

colours = [OKABE_ITO["blue"], OKABE_ITO["orange"], OKABE_ITO["sky_blue"], OKABE_ITO["purple"]]
text_colours = ["white", "black", "black", "black"]

# Before: two tilted, exploded pies with shadows, the look a "3D pie" button gives.
fig, axes = new_figure(ncols=2)
for ax, (year, values) in zip(axes, shares.items()):
    ax.pie(values, labels=methods, colors=colours, explode=[0.1, 0, 0, 0],
           shadow=True, startangle=200)
    ax.set_aspect(0.45)  # squash the circle into a tilted disc
    ax.set_title(year)
save(fig, "4-parts-before")

# After: one 100 per cent bar per year, the same order, every segment labelled.
fig, ax = new_figure(height=3.6)
fig.suptitle("Mobile money overtook cash between 2024 and 2026",
             x=0.01, ha="left", fontweight="bold")
ax.set_title("Share of payments by method, per cent", fontsize=11, fontweight="normal")
years = list(shares)[::-1]  # barh draws the first item at the bottom; this puts 2024 on top
left = [0] * len(years)
for i, method in enumerate(methods):
    values = [shares[year][i] for year in years]
    bars = ax.barh(years, values, left=left, color=colours[i], height=0.6,
                   edgecolor="white", linewidth=1.5)
    ax.bar_label(bars, labels=[f"{v}%" for v in values], label_type="center",
                 color=text_colours[i], fontweight="bold")
    # Name each method once, above its segment in the top bar.
    top_centre = left[-1] + values[-1] / 2
    ax.text(top_centre, len(years) - 0.6, method.replace(" ", "\n"),
            ha="center", va="bottom", color="#333333", fontsize=10)
    left = [l + v for l, v in zip(left, values)]

ax.set_xlim(0, 100)
ax.set_ylim(-0.5, len(years) - 0.5 + 0.55)
ax.xaxis.set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.tick_params(axis="y", left=False)

add_source(fig)
save(fig, "4-parts-after", alt="""
Two stacked bars showing how customers paid, each adding up to 100 per cent.
In 2024: cash 46%, mobile money 30%, card 16%, bank transfer 8%. In 2026: cash
31%, mobile money 44%, card 17%, bank transfer 8%. Mobile money overtook cash;
card and bank transfer barely changed.
""")
PY
python parts.py

The assert near the top stops the script if a year's shares do not add up to 100, which catches a typo before it becomes a chart. Text colour inside each segment follows the colour behind it: white on the dark blue, black on the lighter colours, so every label stays readable.

Stacked bars have a limit too. The first segment (cash) and the last (bank transfer) share a straight edge across both bars, so you can compare them by eye; the segments in the middle start at different points, so compare those by their printed numbers. If the reader's question is about one middle segment, give that segment its own bar chart.

Check it worked

Open charts/4-parts-before.png: two flattened, shadowed pies with names and no numbers. Open charts/4-parts-after.png: two bars, 2024 on top, with 46%, 30%, 16% and 8% in the first and 31%, 44%, 17% and 8% in the second, and the four method names printed once above the top bar.

Step 7 · Check every chart before you share it

A chart is ready to share when it has both files, a source line and alt text. Alt text is what a screen reader says in place of the image, and what appears when an image fails to load on a slow connection. For a chart it should give the type of chart, what is measured and the finding with its key numbers, as each alt= in your scripts does; a title alone is not enough. save() has already written each one to a .alt.txt file.

audit.py checks every published (-after) chart and stops with an error if anything is missing, so you can run it before you send a report:

Bash
cd ~/chart-choice-demo
. .venv/bin/activate
cat > audit.py <<'PY'
"""Check every chart in charts/ before it goes anywhere."""
import sys
from pathlib import Path

from chartkit import SOURCE

PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
problems = 0

for svg in sorted(Path("charts").glob("*-after.svg")):
    name = svg.stem
    png = svg.with_suffix(".png")
    alt = svg.with_name(f"{name}.alt.txt")
    checks = {
        "png": png.exists() and png.read_bytes()[:8] == PNG_SIGNATURE,
        "source line": SOURCE in svg.read_text(encoding="utf-8"),
        "alt text": alt.exists() and 80 <= len(alt.read_text(encoding="utf-8").strip()) <= 600,
    }
    failed = [check for check, ok in checks.items() if not ok]
    problems += len(failed)
    status = "ok" if not failed else "MISSING " + ", ".join(failed)
    if alt.exists():
        status += f"  ({len(alt.read_text(encoding='utf-8').split())}-word alt text)"
    print(f"{name:<16} {status}")

drafts = sorted(p.stem for p in Path("charts").glob("*-before.svg"))
print(f"{len(drafts)} draft charts kept for comparison, not for publishing")
if problems:
    sys.exit(f"{problems} problem(s) found")
PY
python audit.py

To see it catch a problem, move one alt text file aside, run the audit again, then put the file back:

Bash
cd ~/chart-choice-demo
. .venv/bin/activate
mv charts/4-parts-after.alt.txt charts/4-parts-after.alt.bak
python audit.py || echo "audit stopped the release"
mv charts/4-parts-after.alt.bak charts/4-parts-after.alt.txt

When you put a chart on a web page, use the alt text file as the alt attribute, and show the 2x PNG at half its pixel size, for example <img src="4-parts-after.png" width="800" height="360" alt="...">. On the web, prefer the SVG where you can: here every SVG is a fraction of its PNG's size and stays sharp on any screen, which matters to readers on low-end Android phones and prepaid data. Keep the PNGs for slides, documents and chat apps that do not show SVG.

Check it worked

The first audit prints one line per chart, each with ok and the length of its alt text, for example 1-bars-after ok (56-word alt text), then 4 draft charts kept for comparison, not for publishing. The second run prints 4-parts-after MISSING alt text, then 1 problem(s) found and audit stopped the release. Run ls charts and you see an .svg, a .png and, for each -after chart, an .alt.txt file.

When you are done, delete the project with rm -rf ~/chart-choice-demo.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.