Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 57 ยท Saving and Production

Reproducible and Automated Charts

Turn one-off Matplotlib code into repeatable pipelines: chart functions, loops over many datasets, style presets, headless servers, image tests and alt text.

A chart you made by hand once is a drawing. A chart produced by a function that you can run every Monday, on fresh data, on a server with no screen, and get the same look every time, is a report. Most real Matplotlib work ends up in this second form: nightly dashboards, a PDF for each customer, plots for a web page, or figures in a paper that must be rebuilt when the data changes.

This lesson shows the habits that make charts repeatable: functions that return figures, loops that generate many charts without leaking memory, shared styles, fixed sizes for each destination, the headless backend for servers, tests that catch accidental changes, and alt text for accessibility. It builds on pyplot vs the OO API, styles and themes and saving figures.

From drawing to pipeline

Functions One function per chart, figure in, figure out.
Shared style One style for every chart.
Fixed sizes One preset per destination.
Tests Catch changes before readers do.

Same code plus same data gives the same picture.

1 / 2

Write a function that returns a figure

The first rule of automation: wrap each chart in a function that takes data and options, builds the figure with the object-oriented API, and returns the figure. It does not call plt.show() and it does not save. That leaves the caller free to show it, save it, test it or put it into a larger report.

Take the axes as an optional argument. A function that draws into a given ax can be reused as one panel of a bigger dashboard, while a function that creates its own figure is convenient for single charts. A common pattern supports both.

Python A reusable chart function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same function made a stand-alone chart and then filled two panels. Notice that it never touches global pyplot state beyond creating the figure, and that the data comes from outside the function: no hidden globals, so the output depends only on the inputs.

Reproducible means seeded and explicit

A chart is reproducible when the same inputs always give the same pixels. Three habits protect that:

  • Seed every random source with np.random.default_rng(seed), and pass the generator in rather than creating it deep inside helpers.
  • Fix the things Matplotlib would otherwise choose for you: figure size, dpi, axis limits when comparing charts, color mapping (a dict from category to color) and bin edges.
  • Record the environment. Fonts and small rendering details differ between Matplotlib versions and operating systems. Keep the versions in requirements.txt and, if needed, print matplotlib.__version__ into the report footer.

A color dictionary deserves a special mention. If "North" is blue in Monday's chart and green in Tuesday's because the category order changed, readers lose trust. Define REGION_COLORS = {"North": ..., "South": ...} once and look colors up by name.

Generate many charts in a loop

Reports often need one chart per customer, product or day. Build the list of inputs, call your function for each, save, and close the figure. Forgetting plt.close(fig) is the number one cause of memory growth in batch jobs (see Plotting Large Data Fast).

On the site there is no file system, so the example writes into io.BytesIO buffers. On your own machine you would pass a path such as f"out/{name}.png" instead.

Python One chart per product

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every file is exactly 400 by 250 pixels, because figsize=(4, 2.5) at dpi=100 gives 4 x 100 by 2.5 x 100 pixels. The last panel row shows the same three charts together with a shared y axis, which is how you would compare them in a summary. Since each chart gets its color from the dictionary, a product never changes color.

When all charts in a batch need the same y range, compute it once from all the data (ymax = max(v.max() for v in sales.values())) and pass it to every call. Charts with different automatic ranges look similar but mean different things.

Templates, style files and size presets

Style decisions belong in one place. There are three levels.

  1. rc_context with a dictionary, as in the next example. Good for a style that lives inside your code.
  2. A .mplstyle file, a plain text file with lines like axes.spines.top : False. You load it with plt.style.use("report.mplstyle") or with a path. Keep it in your repository so everyone gets the same look. Reading files is not possible on this site, so treat the file format as read-only here.
  3. A package of chart functions that applies the style itself, so callers cannot forget.

Sizes are the other half. Define presets for each destination and use them instead of ad-hoc numbers.

Python
SIZES = {
    "web":    {"figsize": (7, 4),     "dpi": 144},   # 1008 x 576 px
    "report": {"figsize": (6.5, 4),   "dpi": 300},   # fits a page column
    "slide":  {"figsize": (13.33, 7.5), "dpi": 100}, # 16:9
}

Slides need larger fonts than print. A slide preset often changes font.size and lines.linewidth as well; the lesson on styles and themes shows how to change both at once.

Python One chart, three destinations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The three PNG sizes follow from figsize * dpi: 700 by 400, 975 by 600 and 1000 by 560 pixels. The rc_context block applied the style only inside the with, and the last print confirms the global default is untouched, so calling render does not change how later charts look.

Headless servers and scheduled jobs

A server has no display, so interactive backends (Qt, Tk) cannot start. Matplotlib falls back to the non-interactive Agg backend when it detects no display, but do not rely on detection in production. Choose it explicitly before importing pyplot:

Python
import matplotlib
matplotlib.use("Agg")           # must run before "import matplotlib.pyplot"
import matplotlib.pyplot as plt

You can also set the environment variable MPLBACKEND=Agg for the process. Other things to check on a server:

  • Fonts. A minimal Linux image may lack the fonts your style names; Matplotlib then falls back to DejaVu Sans, and text widths change. Install the fonts, or bundle them and register them with matplotlib.font_manager.fontManager.addfont(path).
  • Cache and config folders. If the home directory is read-only (containers), set MPLCONFIGDIR to a writable path, or the first import will be slow and noisy.
  • Threads. Matplotlib's pyplot state is not thread-safe. In a web app, use matplotlib.figure.Figure() directly in each request and never share a figure between threads.
  • No plt.show(). On Agg it does nothing useful (and warns). Save the figure instead.

The Agg backend is also what runs your examples on this site, which is why figures appear as images rather than windows.

Testing figures

Charts can break silently: a library upgrade shifts a legend, a refactor drops a label. Two kinds of tests catch this.

Structure tests check the figure's contents with ordinary assertions. They are stable and fast, and they find most mistakes:

Python
def test_trend_chart_has_title_and_last_label():
    ax = trend_chart(weeks, visits, "Weekly visits", unit="k")
    assert ax.get_title(loc="left") == "Weekly visits"
    assert len(ax.lines) == 1
    assert ax.get_lines()[0].get_ydata()[-1] == visits[-1]

Image comparison tests compare the rendered pixels against a stored baseline picture. Matplotlib ships a pytest decorator for this (matplotlib.testing.decorators.image_comparison), and the plugin pytest-mpl offers @pytest.mark.mpl_image_compare. The baseline images live in your repository, and a tolerance setting absorbs tiny font-rendering differences:

Python
import pytest

@pytest.mark.mpl_image_compare(baseline_dir="baseline", tolerance=5)
def test_trend_chart_image():
    ax = trend_chart(weeks, visits, "Weekly visits", unit="k")
    return ax.figure

Those tests need files on disk, so both snippets are read-only here. Use image tests sparingly (for charts that matter) and run them on the same OS and Matplotlib version that created the baselines.

Accessibility and alt text

A chart is useless to someone who cannot see it unless the page says what it shows. Matplotlib figures are images, so the text alternative must come from you.

  • On the web, always set the alt attribute of the <img>, and describe the message, not the pixels: "Weekly visits grew from 100k to 140k over 12 weeks" beats "line chart".
  • In SVG and PDF files you can embed a title and a description with savefig(metadata=...). Screen readers and search tools can read them.
  • In the chart, use a title that states the finding, direct labels instead of color-only legends, and colors with enough contrast (see Designing Clear Charts).
Python Embedding a description in an SVG

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep the alt text next to the chart function (or return it with the figure) so it is updated whenever the data changes, instead of being copied by hand into a document and forgotten.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a reusable chart function return the figure instead of calling plt.show()?

    A function that only returns the figure leaves every decision about output to the caller, which makes it reusable in scripts, tests and larger reports.
  2. 2. A batch job makes 2,000 charts and its memory keeps growing. What is the most likely fix?

    pyplot keeps every figure it created until it is closed, so unclosed figures accumulate. Closing each figure after saving releases it.
  3. 3. A figure made with figsize=(6, 4) and dpi=150 saved as PNG has what pixel size?

    Pixels are inches times dpi: 6 x 150 = 900 wide and 4 x 150 = 600 tall.
  4. 4. What is the purpose of matplotlib.use("Agg") on a server?

    Agg renders to pixel buffers in memory, so it works without a screen. You then save the figure instead of showing it.
  5. 5. Which test is the most stable way to check that a chart still has the right title and data?

    Structure tests read values straight from the artists, so they do not break when fonts or antialiasing change slightly. Image comparisons are best for a few key charts, with a tolerance.

Summary

  • Write each chart as a function that takes data (and optionally an ax) and returns the figure or axes; save, show and test outside it.
  • Reproducible charts use seeded random data, explicit sizes, fixed colors per category and recorded library versions.
  • In batch loops, save then plt.close(fig); reuse one color dictionary and shared axis limits so charts stay comparable.
  • Put style in one place: rc_context dictionaries, .mplstyle files or a helper package; keep size presets for web, report and slide output.
  • On servers choose the Agg backend explicitly, install fonts, set MPLCONFIGDIR and avoid sharing pyplot state between threads.
  • Test structure with assertions and key charts with image comparison; give every published chart meaningful alt text.

Next, learn to recognize and fix the mistakes that break charts in Pitfalls and Debugging.