Matplotlib Cheat Sheet
Matplotlib plotting reference covering the object-oriented API, subplots, common chart types, and styling options for publication-ready figures.
Basic Plot
Object-oriented figure and axes API.
import matplotlib.pyplot as pltfig, ax = plt.subplots(figsize=(8, 5))ax.plot(x, y, label="sin(x)", color="tab:blue", linewidth=2)ax.set_xlabel("x")ax.set_ylabel("y")ax.set_title("Simple Line Plot")ax.legend()plt.savefig("plot.png", dpi=150, bbox_inches="tight")plt.show()
Subplots
Arrange multiple axes in a grid.
fig, axes = plt.subplots(2, 2, figsize=(10, 8), sharex=True)axes[0, 0].plot(x, y1)axes[0, 1].scatter(x, y2)axes[1, 0].bar(categories, values)axes[1, 1].hist(data, bins=30)fig.tight_layout()
Common Plot Types
Frequently used chart functions.
- ax.plot- line chart
- ax.scatter- scatter plot
- ax.bar / ax.barh- vertical/horizontal bar chart
- ax.hist- histogram of a distribution
- ax.boxplot- box-and-whisker plot
- ax.imshow- display an image or 2D array as a raster
- ax.pie- pie chart
- ax.fill_between- shaded area between two curves
Styling & Limits
Customize the look of a figure.
plt.style.use("seaborn-v0_8-darkgrid") # built-in style sheetax.set_xlim(0, 10)ax.set_ylim(-1, 1)ax.grid(True, alpha=0.3)ax.axhline(0, color="gray", linestyle="--")plt.rcParams["font.size"] = 12 # global rcParams
Twin Axes & Secondary Scales
Plot two series with different units on shared x-axis.
fig, ax1 = plt.subplots(figsize=(8, 5))ax1.plot(dates, temperature, color="tab:red", label="Temp (C)")ax1.set_ylabel("Temperature (C)", color="tab:red")ax1.tick_params(axis="y", labelcolor="tab:red")ax2 = ax1.twinx()ax2.plot(dates, humidity, color="tab:blue", label="Humidity (%)")ax2.set_ylabel("Humidity (%)", color="tab:blue")ax2.tick_params(axis="y", labelcolor="tab:blue")fig.tight_layout()
GridSpec: Mixed Panel Layouts
Compose asymmetric figure layouts beyond a uniform grid.
from matplotlib.gridspec import GridSpecfig = plt.figure(figsize=(10, 6))gs = GridSpec(3, 3, figure=fig, hspace=0.4, wspace=0.3)ax_main = fig.add_subplot(gs[0:2, 0:2]) # large main panelax_top = fig.add_subplot(gs[0, 2])ax_bottom = fig.add_subplot(gs[1, 2])ax_wide = fig.add_subplot(gs[2, :]) # full-width bottom panelax_main.imshow(image_data)ax_wide.plot(timeseries)
Custom Artists & Annotations
Draw shapes and annotate points programmatically.
from matplotlib.patches import Circle, Rectanglefrom matplotlib.collections import PatchCollectionax.add_patch(Rectangle((1, 1), 2, 3, fill=False, edgecolor="tab:green", lw=2))ax.add_patch(Circle((5, 5), radius=1, color="tab:orange", alpha=0.4))ax.annotate( "local max", xy=(peak_x, peak_y), xytext=(peak_x + 1, peak_y + 5), arrowprops=dict(facecolor="black", arrowstyle="->"),)
Animations with FuncAnimation
Build a time-evolving plot and export it as a video/GIF.
from matplotlib.animation import FuncAnimationfig, ax = plt.subplots()line, = ax.plot([], [], lw=2)ax.set_xlim(0, 2 * 3.14159)ax.set_ylim(-1, 1)def update(frame): x = np.linspace(0, 2 * 3.14159, 200) line.set_data(x, np.sin(x + frame * 0.1)) return (line,)anim = FuncAnimation(fig, update, frames=100, interval=30, blit=True)anim.save("wave.mp4", writer="ffmpeg", dpi=150)
Performance & Publication-Quality APIs
Techniques for large datasets and camera-ready figures.
- ax.plot(x, y, rasterized=True)- rasterizes dense vector layers so large PDFs stay small and fast to render
- plt.rcParams['path.simplify']- simplifies line paths with many points for faster rendering
- LineCollection- draws thousands of line segments efficiently in one artist instead of a loop of ax.plot calls
- fig.savefig(..., format='pdf')- vector output preferred for publication over rasterized PNG
- constrained_layout=True- alternative to tight_layout() that handles colorbars and suptitles more robustly
- mplstyle context manager- with plt.style.context('ggplot'): scopes a style to one figure instead of globally
- ax.set_rasterization_zorder(z)- rasterizes only artists below a given z-order, keeping text/axes vector
Use fig, ax = plt.subplots() (the object-oriented API) instead of bare pyplot state-machine calls in any script or function that builds more than one figure — it avoids subtle bugs from plotting onto the wrong 'current' axes.