Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 57 ยท Practice and Interview

Matplotlib Cheat Sheet

A one-page Matplotlib cheat sheet with tables for the object-oriented pattern, chart calls, labels, ticks, legends, subplots, styles, saving and common fixes.

You have now met most of Matplotlib. This page is the quick-reference version: tables you can scan in seconds, a few runnable figures, and links back to the lesson that explains each area. Use it when you remember that a method exists but not its exact name or argument order.

All tables assume these imports and names. ax is an Axes, fig is a Figure, and x, y are NumPy arrays or lists of equal length. The examples target Matplotlib 3.10.

Python
import numpy as np
import matplotlib.pyplot as plt

The pattern in one breath

Make fig, ax = plt.subplots()
Draw Call methods on ax.
Label Title, axes, legend.
Save fig.savefig with a dpi.

Most Matplotlib code is these four steps, repeated.

1 / 2

The object-oriented pattern

Create a figure and axes once, draw on the axes, then save or show. This is the pattern to copy (pyplot vs the Object-Oriented API).

Goal Code Notes
One axes fig, ax = plt.subplots() the default starting point
Set the size plt.subplots(figsize=(6, 4), dpi=100) inches, so pixels = inches times dpi
Tidy layout plt.subplots(layout="constrained") stops labels from being clipped
Draw a line ax.plot(x, y) returns a list of Line2D objects
Show it plt.show() on this site the figure appears as an image
Save it fig.savefig("chart.png", dpi=200) call before show in scripts
Free memory plt.close(fig) important in loops and servers

The names to keep apart: a Figure is the whole canvas, an Axes is one plot inside it (with its data), and an Axis is one number line of an Axes. Read Anatomy of a Figure if the difference still feels fuzzy, and Figure Size, DPI and Layout for the pixel math.

Python The pattern, start to finish

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.

Chart types

Pick the call that matches the question you are answering. Every call below is a method of ax.

Chart Code Use it for
Line ax.plot(x, y) change over an ordered x
Step ax.step(x, y, where="mid") values that jump
Filled band ax.fill_between(x, lo, hi, alpha=0.3) ranges and confidence bands
Bars ax.bar(names, values), ax.barh(...) comparing categories
Stacked bars ax.bar(x, b, bottom=a) parts of a total
Scatter ax.scatter(x, y, s=sizes, c=values) relationships between two variables
Histogram ax.hist(data, bins=20) one distribution
Box / violin ax.boxplot(groups), ax.violinplot(groups) comparing distributions
Pie ax.pie(parts, labels=names) a few parts of a whole
Heatmap ax.imshow(grid), ax.pcolormesh(X, Y, Z) values on a grid
Contours ax.contour(X, Y, Z), ax.contourf(...) a surface seen from above
Error bars ax.errorbar(x, y, yerr=err) uncertainty
Stacked area ax.stackplot(x, a, b, c) parts of a total over time

Details live in Line Plots in Depth, Bar Charts, Scatter Plots, Histograms and Distributions, Box Plots and Violin Plots, Pie, Donut and Stacked Area Charts, Heatmaps and Images and Error Bars and Uncertainty.

Python Six chart calls on one figure

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.

Labels, text and annotations

Goal Code
Axes title ax.set_title("Sales", loc="left", fontsize=14)
Axis labels ax.set_xlabel("Month"), ax.set_ylabel("Units")
Figure title fig.suptitle("Dashboard")
Text at data coordinates ax.text(2, 5, "peak", ha="center")
Text in axes fractions ax.text(0.02, 0.95, "note", transform=ax.transAxes)
Arrow and label ax.annotate("max", xy=(x0, y0), xytext=(x1, y1), arrowprops={"arrowstyle": "->"})
Label bars ax.bar_label(bars, fmt="%.0f")
Math text ax.set_title(r"$y = \alpha x^2$")
Reference lines ax.axhline(0), ax.axvline(3)
Shaded span ax.axvspan(2, 4, alpha=0.2)

Put an r before strings that hold backslashes, so \alpha is not read as an escape. See Titles, Labels, Text and Math and Annotations and Arrows.

Limits, scales and ticks

Goal Code
Set limits ax.set_xlim(0, 10), ax.set_ylim(bottom=0)
Flip an axis ax.invert_yaxis()
Log scale ax.set_xscale("log"), ax.set_yscale("log")
Equal units ax.set_aspect("equal")
Padding around data ax.margins(x=0.05)
Choose ticks ax.set_xticks([0, 5, 10])
Tick text ax.set_xticklabels(["low", "mid", "high"]) (set the ticks first)
Every n units ax.xaxis.set_major_locator(MultipleLocator(5))
Custom format ax.yaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}"))
Rotate labels ax.tick_params(axis="x", rotation=45)
Hide ticks ax.set_xticks([])
Second y scale ax2 = ax.twinx()
Same data, other units ax.secondary_yaxis("right", functions=(f, g))

MultipleLocator lives in matplotlib.ticker, along with MaxNLocator, FuncFormatter and StrMethodFormatter. Dates use matplotlib.dates. Lessons: Limits, Scales and Aspect, Ticks, Locators and Formatters, Shared, Twin and Secondary Axes and Dates and Time Series Charts.

Python Log scale, ticks and a formatter

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.

Legends and grids

Goal Code
Label a line ax.plot(x, y, label="2024")
Show the legend ax.legend()
Place it ax.legend(loc="upper left"), loc="best" is the default
Outside the plot ax.legend(loc="upper left", bbox_to_anchor=(1.02, 1))
Columns ax.legend(ncol=2, frameon=False)
Hide an entry label="_nolegend_"
Custom entries ax.legend(handles=[Line2D([], [], color="C0", label="a")])
One legend for the figure fig.legend(loc="outside right upper")
Grid ax.grid(True, linestyle=":", alpha=0.5)
Grid behind data ax.set_axisbelow(True)

Only artists that have a label appear in the legend. Line2D and Patch come from matplotlib.lines and matplotlib.patches. See Legends and Grids.

Subplots and layouts

Goal Code
Grid of axes fig, axs = plt.subplots(2, 3) (a 2D array of Axes)
One row or column plt.subplots(1, 3) returns a 1D array
Loop over all for ax in axs.flat:
Share an axis plt.subplots(2, 1, sharex=True)
Named layout fig, axd = plt.subplot_mosaic("AAB;CCB")
Uneven sizes plt.subplots(1, 2, width_ratios=[3, 1])
Hide an unused axes axs[1, 2].set_visible(False)
Small inset ax.inset_axes([0.6, 0.1, 0.3, 0.3])
Spacing layout="constrained" or fig.tight_layout()

With nrows=1 and ncols=1, subplots returns a single Axes, not an array. Pass squeeze=False when you want a 2D array in every case. See Multiple Subplots and GridSpec and subplot_mosaic.

Python A mosaic with a shared axis

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.

Colors, styles and themes

Goal Code
Color color="tab:blue", "#1f77b4", (0.1, 0.4, 0.8) or "C0"
Line style linestyle="--" (also ":", "-.")
Width and markers linewidth=2, marker="o", markersize=5
Format string ax.plot(x, y, "ro--") (color, marker, style)
Transparency alpha=0.5
Draw order zorder=3
Colormap cmap="viridis"
Colorbar fig.colorbar(im, ax=ax, label="value")
Log or centered colors LogNorm(), TwoSlopeNorm(vcenter=0)
Built-in look plt.style.use("ggplot")
Change one default plt.rcParams["font.size"] = 12
Temporary settings with plt.rc_context({"lines.linewidth": 3}):
Color cycle plt.rcParams["axes.prop_cycle"] = cycler(color=[...])
Remove spines ax.spines[["top", "right"]].set_visible(False)

Prefer sequential maps such as viridis for ordered values, a diverging map with TwoSlopeNorm when zero matters, and never jet. See Colors, Line Styles and Markers, Colormaps and Color Normalization, Styles, rcParams and Themes and Designing Clear Charts.

Python A style context and a colorbar

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.

Saving figures

Goal Code
PNG for the web fig.savefig("a.png", dpi=150)
Vector for print fig.savefig("a.svg") or "a.pdf"
Crop empty margins fig.savefig("a.png", bbox_inches="tight")
Transparent background fig.savefig("a.png", transparent=True)
Into memory fig.savefig(buf, format="png") with buf = io.BytesIO()
Rasterize heavy layers ax.scatter(x, y, rasterized=True)

The file type comes from the extension unless you pass format=. Use PNG for photos and dense plots, SVG or PDF for lines and text that must stay sharp. See Saving Figures and Plotting Large Data Fast.

Python Saving to memory 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.

Common problems and fixes

Symptom Likely cause Fix
Two charts drawn on top of each other reused the same current figure create a new fig, ax and plt.close(fig) when done
Labels cut off at the edge default layout layout="constrained" or bbox_inches="tight"
set_xticklabels shows wrong labels ticks were not fixed first call set_xticks before set_xticklabels
AttributeError: 'numpy.ndarray' object has no attribute 'plot' subplots with several axes returns an array index it: axs[0] or axs[0, 1]
Everything squeezed at the bottom one huge outlier log scale, or set_ylim
Scatter colors look random or wrong c= got a list whose length does not match the points give c one value per point, or use color="C0" for a single color
Legend is empty no label= on the artists add labels, or pass handles and labels
Figures pile up in a loop never closed plt.close(fig) after each save
Fuzzy text in exported images low dpi or a raster format raise dpi or save as SVG or PDF
Dates look jumbled long date strings on the axis fig.autofmt_xdate() or the mdates formatters

More cases, with the tracebacks, are in Pitfalls and Debugging.

Python Fixing a clipped, crowded axis

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.

Habits worth keeping

  • Use fig, ax = plt.subplots(...) and call methods on ax. Reserve bare plt. calls for plt.show(), plt.subplots() and plt.close().
  • Choose the chart for the question: lines for trends, bars for comparing categories, histograms for distributions, scatter for relationships.
  • Label axes with units, give every chart a title that states the finding, and label lines directly when you can.
  • Set the size and dpi once, use a style or rc_context for a consistent look, and plt.close(fig) in loops.
  • Test a new idea on a tiny synthetic dataset with a fixed seed before you point it at real data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does plt.subplots(2, 3) return?

    subplots returns the Figure and the Axes. With more than one row and column the Axes arrive as a 2D array, so you index them like axs[0, 1] or loop over axs.flat.
  2. 2. Which call saves a figure with its empty margins trimmed?

    bbox_inches="tight" shrinks the saved area to fit the drawn artists. The other options are not savefig arguments or pyplot functions.
  3. 3. You call ax.set_xticklabels(["low", "mid", "high"]) and the labels land on the wrong ticks. What is the best fix?

    Labels are matched to whichever ticks exist at that moment. Fixing the tick positions first makes the pairing explicit.
  4. 4. A figure inside a loop of 500 charts uses more and more memory. What is the most likely cause?

    pyplot keeps a reference to every figure you create until you close it. Call plt.close(fig) after saving each one.

Summary

  • Start every chart with fig, ax = plt.subplots(...), draw with ax methods, label, then save or show.
  • Each chart type is one method: plot, bar, scatter, hist, boxplot, imshow, errorbar and friends.
  • Control the view with limits, scales and tick locators; label with titles, axis labels, text and annotations.
  • Legends need labels, subplots return arrays of Axes, and layout="constrained" fixes most overlap.
  • Style with built-in styles, rcParams and rc_context; save with savefig and a sensible dpi, and close figures you no longer need.

Want more? Revisit the Practice Exercises or the Interview Questions, or jump back to What Is Matplotlib? to start the course again.