Matplotlib Cheat Sheet

Complete reference guide for creating plots, customizing appearance, and managing axes layouts in Matplotlib for data visualization in Python.


Setup and Basic Plot Creation

Action Code Example Description
Import Libraries import matplotlib.pyplot as plt
import numpy as np
Standard convention for importing Matplotlib's plotting interface and NumPy.
Enable Inline Plotting (Jupyter) %matplotlib inline An IPython magic command to display figures directly within the notebook output.
Create a Figure and Axes fig, ax = plt.subplots() The recommended starting point. Creates a Figure object (the canvas) and an Axes object (the coordinate system for plotting).
Create a Figure with a Specific Size fig = plt.figure(figsize=(8, 4)) Creates a Figure with a width of 8 inches and a height of 4 inches.
Manually Add Axes to a Figure ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) Adds an Axes instance to the figure canvas at a specific location [left, bottom, width, height] as fractions of the canvas size.
Save a Figure fig.savefig("graph.png", dpi=100) Saves the figure to a file. The format is inferred from the extension. dpi sets the resolution.

Common Plot Types

Action Code Example Description
Line Plot ax.plot(x, y1, color="blue", label="y(x)") The most common plot type for drawing lines and markers connecting data points.
Bar Plot ax.bar(n, N.pmf(n)) Creates a bar chart, often used for histograms or categorical data.
Scatter Plot ax.scatter(x1, x2) Plots individual data points without connecting lines.
Contour / Colormap Plot c = ax.pcolor(X, Y, Z, cmap=mpl.cm.bwr) Visualizes 2D data (a matrix Z over coordinates X, Y) using color. contour and contourf are similar.
3D Surface Plot ax = fig.add_subplot(1, 1, 1, projection='3d')
p = ax.plot_surface(X, Y, Z, cmap=cmap)
Creates a 3D plot. Requires creating an Axes object with a 3D projection.

Customizing Plot Appearance

Action Code Example Description
Set Line Properties ax.plot(x, y, linewidth=2, linestyle='--', marker='o') Controls the appearance of lines. Common arguments include linewidth (or lw), linestyle (or ls), color, and marker.
Set Labels and Title ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("My Plot")
Sets the text labels for the x-axis, y-axis, and the title of the Axes object.
Add a Legend ax.legend(loc=2) Displays the legend for plots that have a label argument. loc controls the position (e.g., 2 for upper-left).
Add Text and Annotations ax.text(x, y, "Label")
ax.annotate("Annotation", xy=(1, 0), xytext=(20, 50), ...)
Adds text to the plot at specified coordinates. annotate can also draw an arrow.
Use LaTeX for Math ax.set_xlabel(r"$\alpha_i$") Renders mathematical expressions using LaTeX by enclosing them in $ signs within a raw string (r"...").
Set Axis Range ax.set_xlim(-5, 5)
ax.set_ylim(-1, 1)
ax.axis('tight')
Manually sets the limits for the x and y axes. axis('tight') adjusts limits to fit the data snugly.
Set Axis Ticks ax.set_xticks([-np.pi, 0, np.pi])
ax.set_xticklabels([r'$-\pi$', '0', r'$\pi$'])
Manually sets the position and labels of the axis ticks.
Use Tick Locators ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(4)) Uses a ticker object for automatic, rule-based placement of ticks.
Add a Grid ax.grid(color="blue", which="major", linestyle=':') Adds grid lines corresponding to the axis ticks.
Modify Axis Spines ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data', 0))
Modifies the lines that form the box around the plot area. You can change their color or move them.
Create a Twin Axis ax2 = ax1.twinx() Creates a second y-axis that shares the same x-axis, useful for plotting data with different scales.

Advanced Axes Layouts

Action Code Example Description
Create a Grid of Subplots fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True) The most common way to create a figure with a grid of Axes objects. sharex makes plots in the same column share an x-axis.
Create an Inset Plot ax_insert = fig.add_axes([0.5, 0.5, 0.38, 0.42]) Manually adds a smaller Axes object inside a larger one.
Create a Complex Grid (GridSpec) gs = mpl.gridspec.GridSpec(2, 2, width_ratios=[4, 1])
ax0 = fig.add_subplot(gs[0, 0])
The most flexible way to create complex grid layouts where rows and columns can have different sizes.

Essential Import Statements

import matplotlib.pyplot as plt
import numpy as np
# Object-oriented interface
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_title('Title')

Legacy Approach (Functional)

# Procedural interface (less recommended for complex plots)
plt.plot(x, y)
plt.xlabel('x label')
plt.ylabel('y label')
plt.title('Title')

Common Customizations

Color Schemes and Styles

# Set color
plt.plot(x, y, color='red')  # Named color
plt.plot(x, y, color='#FF5733')  # Hex
plt.plot(x, y, color=(1, 0.5, 0))  # RGB tuple

# Line styles
plt.plot(x, y, linestyle='-')   # Solid
plt.plot(x, y, linestyle='--')  # Dashed
plt.plot(x, y, linestyle=':')   # Dotted
plt.plot(x, y, linestyle='-.')  # Dash-dot

# Markers
plt.plot(x, y, marker='o')  # Circle
plt.plot(x, y, marker='s')  # Square
plt.plot(x, y, marker='^')  # Triangle

Multiple Subplots

# Create subplots
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 8))

# Multiple ways to create subplots
fig, axes = plt.subplots(2, 3)
ax = plt.subplot2grid((3, 3), (0, 0), rowspan=2, colspan=2)

Advanced Layouts

# Constrained layout (recommended)
fig, axs = plt.subplots(2, 2, constrained_layout=True)

# Tight layout with padding
plt.tight_layout(pad=2.0, h_pad=1.0, w_pad=1.0)

# Custom spacing
fig.subplots_adjust(hspace=0.3, wspace=0.3)

Statistical Plotting

# Standard error bars
plt.errorbar(x, y, yerr=errors, xerr=errors, fmt='o')

# Histograms
n, bins, patches = plt.hist(data, bins=20, alpha=0.7, color='blue')

# Box plots
plt.boxplot([data1, data2], labels=['Group 1', 'Group 2'])

# Scatter plots with bubbles
plt.scatter(x, y, s=area, c=temperature, alpha=0.6, cmap='viridis')

Saving and Exporting

# Multiple formats
plt.savefig('plot.pdf', dpi=300, bbox_inches='tight')
plt.savefig('plot.svg', facecolor='white', transparent=False)
plt.savefig('plot.png', dpi=150, format='png')

# High-quality publication
plt.savefig('publication_figure.png',
            dpi=600,
            bbox_inches='tight',
            facecolor='white',
            edgecolor='none')

Style Sheets and Themes

# Built-in styles
plt.style.use('default')
plt.style.use('classic')
plt.style.use('fivethirtyeight')

# Custom style
with plt.style.context('seaborn-v0_8'):
    plt.plot(x, y)

This comprehensive Matplotlib cheatsheet provides the essential techniques for creating publication-quality plots and visualizations in Python. Mastering these techniques will greatly enhance your data visualization skills.

Updated: January 15, 2025
Author: Danial Pahlavan
Category: Data Science & Visualization