Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 57 ยท Saving and Production

Pitfalls and Debugging

Fix the Matplotlib problems everyone hits: overlapping figures, leaking state, cut-off labels, axes vs axis, odd scatter colors, mutable defaults and warnings.

Almost every Matplotlib problem looks mysterious the first time and obvious the second. A chart that contains lines from an earlier cell, a label that is cut off in the saved file, a scatter plot whose colors make no sense, a traceback that says an array has no attribute plot: each of these has a short, well-known cause. Knowing the causes turns an hour of confusion into a one-minute fix.

This lesson is a field guide. For each pitfall you see the symptom, the reason, and the repair. Then you get a debugging routine that works for problems not listed here. It assumes you know pyplot vs the OO API and the anatomy of a figure.

Four families of trouble

Hidden state pyplot remembers the current figure.
Clipping Labels outside the canvas disappear.
Wrong inputs Colors and shapes are guessed from data.
Warnings Messages that point at the real mistake.

Read the message first. It is usually right.

1 / 2

Pitfall 1: lines from earlier cells, or figures piling up

Symptom. A new chart contains lines you did not draw in this cell, two charts are drawn on top of each other, or you get a figure full of overlapping text.

Cause. The plt.plot(...) style of calling has state: it draws on "the current axes", and if none exists it creates one. Call it again and it reuses the same axes. In a notebook or a long-lived session, the current axes may survive from an earlier cell. The same thing happens to plt.title, plt.xlabel and plt.legend.

Fix. Create the figure and axes yourself at the start of each chart and draw on that ax. If you really use pyplot style, start every chart with plt.figure() and finish with plt.show() or plt.close().

Python State leaking between charts

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 first block put both curves on one axes, because plt.plot found the current axes and reused it. The second block keeps two objects, so nothing can leak between them. Remember to close figures you no longer need; see Plotting Large Data Fast.

Pitfall 2: axes vs axis, and arrays of axes

Symptom. AttributeError: 'numpy.ndarray' object has no attribute 'plot', or TypeError: 'Axes' object is not subscriptable.

Cause. plt.subplots() returns a single Axes when you ask for one panel, a 1D array for a row or column, and a 2D array for a grid. Code that assumes the wrong shape fails. Also remember the vocabulary: an Axes is the whole plotting area (the thing with .plot), while an axis (ax.xaxis, ax.yaxis) is one of its number lines, the thing that owns the ticks and the label formatter. Mixing them up leads to calls like ax.xaxis.plot, which do not exist.

Fix. Print axes.shape if you are unsure. Use squeeze=False to always get a 2D array, or np.atleast_1d(axes).ravel() / axes.flat to loop over panels no matter the layout.

Python Reading the error messages

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 messages name the exact problem: a NumPy array is not an Axes, an Axes cannot be indexed, and x and y must have the same length. The last block shows the reliable way to loop over any grid, with grid.flat.

Pitfall 3: labels cut off, or too much blank space

Symptom. A long axis label, a rotated tick label or a legend placed outside the axes is cut off in the saved PNG, although it looked fine on screen. Or the saved image has big white margins.

Cause. Layout is computed for the figure canvas. Anything that sticks out beyond the canvas is clipped on save. Margins are fixed fractions unless you ask Matplotlib to adjust them.

Fix. Use layout="constrained" when creating the figure (it moves axes to make room for labels and legends), or fig.tight_layout(). For a one-off save, fig.savefig("name.png", bbox_inches="tight") expands the saved area to include everything. See Figure Size, DPI and Layout.

Pitfall 4: unexpected scatter colors

Symptom. A scatter call with c= gives colors you did not choose, for example points in yellow and purple although you wrote a red RGB triple.

Cause. The c argument is overloaded. A single color name is a color for every point. A list of numbers with one number per point is data to be mapped through a colormap. A list of three or four numbers is ambiguous: it can be one RGB color or three values for three points. Matplotlib chooses value mapping when the length matches the number of points, and it does not always warn you. Use color= (or facecolor=) for fixed colors, and c= only for mapped values or full lists of colors.

Python Three points, three meanings of c

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 left panel shows one yellow and two purple points, not three red ones, because the three numbers were treated as data for the default colormap (1.0 is yellow, 0.0 is purple). The middle panel is what the author meant. The printed warning count is 0 in the version used here: the mix-up is silent, which is why it is worth knowing.

Pitfall 5: shared mutable defaults

Symptom. A helper that you call several times gets slower, or its legend, labels or styles accumulate from call to call.

Cause. This is a Python rule, not a Matplotlib one: a default argument such as labels=[] or style={} is created once, when the function is defined, and every call that omits it shares that same object. Chart helpers fall into this trap because they love defaults for labels, colors and options. Another variant is def f(ax=plt.gca()), which grabs one axes when the function is defined and keeps drawing on it forever.

Fix. Use None as the default and create the value inside the function.

Python The default that remembers

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 "bad" helper returned a longer list on every call, so it is quietly remembering earlier charts. The good one starts clean each time.

Common warnings and what they mean

Warnings are not noise. Most of them point straight at the mistake.

Message (shortened) Meaning and fix
No artists with labels found to put in legend You called legend() but no line or marker has a label=. Add labels, or pass handles explicitly.
FigureCanvasAgg is non-interactive, and thus cannot be shown You called plt.show() on a non-interactive backend. Save the figure, or ignore it in headless code.
More than 20 figures have been opened Figures are not being closed. Call plt.close(fig) in loops.
Attempt to set non-positive xlim on a log-scaled axis Your data or limits include zero or negative values on a log axis. Filter the data or use symlog.
Tight layout not applied The labels do not fit even after shrinking the axes. Increase figsize or shorten the text.
Glyph ... missing from font(s) A character (for example an emoji) is not in the chosen font. Pick a font that has it.
FixedFormatter should only be used together with FixedLocator You set tick labels without fixing the tick positions. Call set_xticks first, then set_xticklabels.
Mean of empty slice / invalid value encountered NumPy warnings from empty or all-NaN data. Check your filter, not Matplotlib.

You can turn warnings into errors while debugging so that a traceback shows exactly where they come from: warnings.simplefilter("error").

Python Provoking and reading warnings

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.

A debugging routine that always works

When something looks wrong and no table row matches, work through these steps.

  1. Read the full message. The last line of a traceback names the problem; the line above it names your code.
  2. Inspect the inputs. Print x.shape, y.shape, x.dtype, np.isnan(y).sum(), x.min() and x.max(). Many "Matplotlib bugs" are NaNs, strings that look like numbers, or an array with a surprising shape.
  3. Inspect the figure. fig.get_axes(), ax.lines, ax.collections, ax.get_xlim() and ax.get_legend_handles_labels() tell you what is actually on the chart. Often the data is there but the limits hide it.
  4. Shrink the problem. Delete code until the smallest example still goes wrong. Half of the bugs disappear in this step because you find the line you did not mean.
  5. Reset the state. plt.close("all"), restart the kernel or cell, and run again from the top. If it works, something stale was leaking.
  6. Read the docstring. help(ax.scatter) or ax.scatter? in a notebook; the argument you misunderstood is usually described there.

If an axis range looks wrong, remember that Matplotlib autoscales from the data it has seen; calling ax.relim() followed by ax.autoscale_view() recomputes it after you change artists by hand. For chart-type problems, you can compare against the matching lesson, such as Scatter Plots or Ticks, Locators and Formatters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a second plt.plot call in a new notebook cell sometimes draw on top of an earlier chart?

    The pyplot interface is stateful: it draws on the current axes. Creating a fresh figure and axes with plt.subplots() at the start of every chart avoids it.
  2. 2. plt.subplots(2, 2) returns axes. Which loop works for every panel?

    With a 2D array, iterating directly yields rows (arrays), not Axes. axes.flat walks over every Axes in a grid of any shape.
  3. 3. What does scatter(x, y, c=[1, 0, 0]) do for exactly three points?

    When the length of c matches the number of points, the numbers are data for the colormap. Use color=(1, 0, 0) for a fixed red.
  4. 4. What is wrong with def chart(data, labels=[])?

    Default values are evaluated once at definition time. Use labels=None and create a new list inside the function.
  5. 5. Your saved PNG cuts off a long y label. Which is the most direct fix?

    Anything outside the canvas is clipped. Constrained layout makes room for labels, and bbox_inches="tight" enlarges the saved area to include them.

Summary

  • pyplot is stateful: create fig, ax = plt.subplots() for every chart and close figures you are finished with.
  • subplots returns one Axes, a 1D array or a 2D array depending on the arguments; use axes.flat or squeeze=False. An Axes is the plot, an axis is one number line.
  • Clipped labels are fixed with layout="constrained", tight_layout() or bbox_inches="tight".
  • Use color= for one fixed color and c= for per-point colors or values; a three-number c for three points is ambiguous.
  • Never use mutable defaults such as labels=[]; use None and build the value inside.
  • Treat warnings as clues, inspect data and artists, shrink the problem, reset state and read the docstring.

Next, see where Matplotlib fits among other plotting libraries in The Matplotlib Ecosystem.