Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 76 ยท Visualization and Storytelling

Matplotlib for Analysts

Use matplotlib's object-oriented API for analysis: figures and axes, subplots, annotations, styles, small multiples and saving charts, with live examples.

The Python matplotlib lesson shows how to draw your first line chart with plt.plot. That quick style is fine for a one-off look, but analysis work quickly outgrows it: you want two charts side by side, a consistent look across a report, a note pointing at the interesting spike, and a file you can drop into a slide. All of that is easier once you understand how matplotlib is organized.

In this lesson you will learn the figure and axes model, build subplots and small multiples, annotate a chart so it tells a story, apply a style once for the whole project, and save the result. The examples draw from generated data, so every run produces the same pictures. For design choices behind the code, keep Principles of Effective Visualization in mind.

Figure and axes

A matplotlib chart is built from nested objects:

  • Figure: the whole canvas (the "page"). It has a size, a resolution and a title for the whole picture.
  • Axes: one plot inside the figure, with its own x-axis, y-axis, title and data. A figure can hold many axes. (Despite the plural name, one Axes is a single chart.)
  • Artists: everything you see, such as lines, bars, text and ticks.
flowchart TD
    F["Figure<br/>(the canvas)"] --> A1["Axes 1<br/>(one chart)"]
    F --> A2["Axes 2<br/>(another chart)"]
    A1 --> L["Line, bars, text"]
    A1 --> X["x-axis and y-axis"]
    A2 --> S["Scatter points"]

A figure holds one or more axes; every chart element belongs to one axes.

The recommended habit is the object-oriented style: create the figure and axes explicitly with plt.subplots() and call methods on the axes. It is just as short as plt.plot, and it is always clear which chart you are modifying.

Python The object-oriented style: fig, ax = plt.subplots()

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.

Methods on an axes start with set_ (set_title, set_xlabel, set_xlim) when they configure it, and with a verb (plot, bar, scatter, hist, text, annotate) when they draw something. If you learn those two families, you can find almost anything.

Subplots and small multiples

plt.subplots(rows, cols) returns one figure and an array of axes. Use it to compare related views, or to repeat the same chart for each group. The second idea is called small multiples: one small chart per category, all with the same scales so they can be compared at a glance. It is usually better than cramming ten lines into one plot.

Python Small multiples with shared axes

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.

Because sharex=True and sharey=True, all four panels use the same axes. The East line is visibly steepest and the West line is flat, without a legend or any color coding. When panels have different scales the comparison is lost, so share axes unless a group's range is so different that the chart becomes unreadable.

For irregular layouts, fig.add_gridspec() or plt.subplot_mosaic() lets you describe the arrangement, for example one wide chart on top and two small ones below.

Annotations: point at the story

A chart with no guidance makes the reader hunt. Add annotations for the one or two things that matter: a spike, a policy change, a threshold. ax.annotate draws text with an arrow, ax.axvline and ax.axhline draw reference lines, and ax.axvspan shades a period.

Python Annotating an event, a threshold and a shaded period

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 annotations short and place them near the thing they describe. If you need a paragraph, it belongs in the report text, not in the chart.

Styles and defaults

Setting the same font size, grid and colors on every chart is tedious and error-prone. Matplotlib has two tools for this:

  • Style sheets: plt.style.use("ggplot") applies a whole look; plt.style.available lists the choices. Styles such as seaborn-v0_8-whitegrid and fivethirtyeight are popular starting points.
  • rcParams: a dictionary of defaults. Set it once at the top of your script or in a shared module so every chart matches.
Python One rcParams block for the whole project

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.

You can also apply a style temporarily with with plt.style.context("ggplot"):, which restores the previous settings afterwards. Do not mix many styles in one report; consistency is what makes charts feel professional.

Color and size choices that save time

A few details prevent most "why does it look wrong?" moments:

  • figsize is in inches. Choose it for the destination: about 7 by 4 for a report column, 10 by 5.6 for a widescreen slide. Then font sizes are correct without scaling.
  • tight_layout() or constrained_layout=True (in plt.subplots) stops labels from overlapping or being cut off.
  • Colormaps (cmap="viridis") suit continuous values; viridis is perceptually even and color-blind safe. Avoid jet.
  • Text should be at least about 10 points at the final size.

Saving figures

On your own computer you save a figure with fig.savefig("chart.png", dpi=200, bbox_inches="tight"). Use PNG for slides and documents, and SVG or PDF for vector graphics that stay sharp when scaled. Always call savefig before plt.show(), because show may clear the figure in some environments. In the browser there is no file system, but you can save to an in-memory buffer to see what would be written:

Python Saving to a buffer instead of a file

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.

In a script you would write fig.savefig("sales.png") and use the file in your report. Close figures you no longer need with plt.close(fig); a long loop that creates hundreds of figures without closing them uses a lot of memory.

Tip: Wrap your chart code in functions that take data and an ax (def plot_trend(ax, df): ...). The same function can then draw on a standalone figure or on one panel of a bigger layout.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In matplotlib, what is an Axes?

    A Figure is the canvas; an Axes is a single plot on it. One figure can hold many Axes objects.
  2. 2. What do sharex=True and sharey=True do in plt.subplots?

    Shared axes keep the scales identical, which is the whole point of small multiples.
  3. 3. Which method draws an arrow pointing at a data point with a text label?

    annotate combines text and an optional arrow, with the target in xy and the text position in xytext.
  4. 4. Why set rcParams once at the top of a project?

    Central defaults keep a report consistent and remove repeated styling lines.
  5. 5. When should you call fig.savefig relative to plt.show()?

    In many environments show() closes the figure when its window or output is done, so save first.

Summary

  • Use the object-oriented style: fig, ax = plt.subplots(...), then call methods on ax.
  • A figure contains axes; each axes is one chart. set_* methods configure, verb methods draw.
  • Small multiples with shared axes beat one crowded chart for comparing groups.
  • Annotate the one or two things that matter with annotate, axvline, axhline and axvspan.
  • Set a house style once with rcParams or a style sheet; choose figsize for the destination.
  • Save with fig.savefig(...) before show() and close figures you no longer need.

Next: Showing Distributions and Uncertainty, where a single line or average is not enough.