Matplotlib Cheatsheet
Installation
| Platform | Command |
|---|
| Ubuntu/Debian | sudo apt install python3-matplotlib or pip3 install matplotlib |
| RHEL/Fedora | sudo dnf install python3-matplotlib or pip3 install matplotlib |
| macOS | brew install matplotlib or pip3 install matplotlib |
| Windows | pip install matplotlib |
| Conda (All) | conda install matplotlib |
| Virtual Env | python -m venv myenv && source myenv/bin/activate && pip install matplotlib |
| With All Features | pip install matplotlib[all] |
| Verify Install | python -c "import matplotlib; print(matplotlib.__version__)" |
Basic Commands
| Command | Description |
|---|
import matplotlib.pyplot as plt | Import pyplot module (standard convention) |
plt.plot(x, y) | Create a basic line plot |
plt.scatter(x, y) | Create a scatter plot |
plt.bar(x, height) | Create a vertical bar chart |
plt.barh(y, width) | Create a horizontal bar chart |
plt.hist(data, bins=30) | Create a histogram with 30 bins |
plt.xlabel('Label') | Set x-axis label |
plt.ylabel('Label') | Set y-axis label |
plt.title('Title') | Set plot title |
plt.legend() | Display legend for labeled data |
plt.grid() | Add grid lines to plot |
plt.xlim(min, max) | Set x-axis limits |
plt.ylim(min, max) | Set y-axis limits |
plt.show() | Display the plot in a window |
plt.savefig('file.png') | Save plot to file |
plt.close() | Close current figure and free memory |
plt.figure(figsize=(10, 6)) | Create new figure with size in inches |
fig, ax = plt.subplots() | Create figure and single axes (OO interface) |
fig, axes = plt.subplots(2, 2) | Create 2x2 grid of subplots |
plt.subplot(2, 2, 1) | Create subplot in 2x2 grid, position 1 |
Plot Customization
| Command | Description |
|---|
plt.plot(x, y, 'r--') | Red dashed line (color + linestyle shorthand) |
plt.plot(x, y, linewidth=2) | Set line width |
plt.plot(x, y, color='#FF5733') | Set color using hex code |
plt.plot(x, y, marker='o') | Add circular markers at data points |
plt.plot(x, y, markersize=10) | Set marker size |
plt.plot(x, y, alpha=0.5) | Set transparency (0=transparent, 1=opaque) |
plt.plot(x, y, label='Data') | Add label for legend |
plt.scatter(x, y, s=100, c=colors) | Scatter with size and color arrays |
plt.scatter(x, y, cmap='viridis') | Use colormap for scatter colors |
plt.xticks(rotation=45) | Rotate x-axis tick labels 45 degrees |
plt.xticks([0, 1, 2], ['A', 'B', 'C']) | Set custom tick positions and labels |
plt.grid(alpha=0.3, linestyle='--') | Customize grid appearance |
plt.legend(loc='upper right') | Position legend in specific location |
plt.tight_layout() | Adjust spacing to prevent label overlap |
plt.axis('equal') | Equal aspect ratio for x and y axes |
Advanced Usage
| Command | Description |
|---|
plt.errorbar(x, y, yerr=err) | Plot with error bars |
plt.fill_between(x, y1, y2) | Fill area between two curves |
plt.contour(X, Y, Z) | Create contour plot from 2D data |
plt.contourf(X, Y, Z, levels=20) | Filled contour plot with 20 levels |
plt.imshow(data, cmap='hot') | Display 2D array as image/heatmap |
plt.colorbar() | Add colorbar to current plot |
plt.boxplot(data) | Create box and whisker plot |
plt.violinplot(data) | Create violin plot (distribution shape) |
plt.pie(sizes, labels=labels, autopct='%1.1f%%') | Pie chart with percentage labels |
ax.twinx() | Create second y-axis sharing same x-axis |
plt.semilogx(x, y) | Plot with logarithmic x-axis |
plt.semilogy(x, y) | Plot with logarithmic y-axis |
plt.loglog(x, y) | Plot with both axes logarithmic |
plt.step(x, y, where='mid') | Step plot with steps at midpoints |
plt.stem(x, y) | Create stem plot (lollipop chart) |
plt.hexbin(x, y, gridsize=30) | Hexagonal binning plot |
plt.streamplot(X, Y, U, V) | Streamlines for vector field |
plt.quiver(X, Y, U, V) | Arrow plot for vector field |
ax.set_xscale('log') | Set x-axis to logarithmic scale (OO) |
ax.annotate('text', xy=(x,y)) | Add annotation at specific point |
3D Plotting
| Command | Description |
|---|
from mpl_toolkits.mplot3d import Axes3D | Import 3D plotting toolkit |
ax = fig.add_subplot(111, projection='3d') | Create 3D axes |
ax.plot3D(x, y, z) | 3D line plot |
ax.scatter3D(x, y, z) | 3D scatter plot |
ax.plot_surface(X, Y, Z) | 3D surface plot |
ax.plot_wireframe(X, Y, Z) | 3D wireframe plot |
ax.contour3D(X, Y, Z) | 3D contour plot |
ax.set_xlabel('X') | Set 3D x-axis label |
ax.view_init(elev=30, azim=45) | Set 3D viewing angle |
Object-Oriented Interface
| Command | Description |
|---|
fig, ax = plt.subplots() | Create figure and axes objects |
ax.plot(x, y) | Plot using axes object |
ax.set_xlabel('Label') | Set x-axis label (OO method) |
ax.set_ylabel('Label') | Set y-axis label (OO method) |
ax.set_title('Title') | Set title (OO method) |
ax.set_xlim(min, max) | Set x-axis limits (OO method) |
ax.set_ylim(min, max) | Set y-axis limits (OO method) |
ax.legend() | Add legend (OO method) |
ax.grid(True) | Enable grid (OO method) |
ax.set_aspect('equal') | Set aspect ratio |
fig.suptitle('Main Title') | Set overall figure title |
fig.tight_layout() | Adjust subplot spacing |
ax.spines['top'].set_visible(False) | Hide top spine/border |
ax.tick_params(labelsize=12) | Customize tick parameters |
Configuration
Runtime Configuration (rcParams)
import matplotlib.pyplot as plt
# Set default figure size
plt.rcParams['figure.figsize'] = (10, 6)
# Set default DPI
plt.rcParams['figure.dpi'] = 100
# Set default font size
plt.rcParams['font.size'] = 12
# Set default line width
plt.rcParams['lines.linewidth'] = 2
# Set default colormap
plt.rcParams['image.cmap'] = 'viridis'
# Use LaTeX for text rendering
plt.rcParams['text.usetex'] = True
# Set backend
plt.rcParams['backend'] = 'TkAgg'
Style Sheets
# Use built-in style
plt.style.use('seaborn-v0_8')
plt.style.use('ggplot')
plt.style.use('dark_background')
# List available styles
print(plt.style.available)
# Use multiple styles (later ones override earlier)
plt.style.use(['seaborn-v0_8', 'seaborn-v0_8-poster'])
# Temporary style context
with plt.style.context('dark_background'):
plt.plot(x, y)
Configuration File (matplotlibrc)
Create ~/.config/matplotlib/matplotlibrc (Linux/macOS) or %USERPROFILE%\.matplotlib\matplotlibrc (Windows):
# Figure properties
figure.figsize: 10, 6
figure.dpi: 100
# Font properties
font.size: 12
font.family: sans-serif
# Line properties
lines.linewidth: 2
lines.markersize: 8
# Grid properties
grid.alpha: 0.3
grid.linestyle: --
# Legend properties
legend.frameon: False
legend.loc: best
# Axes properties
axes.grid: True
axes.titlesize: 14
axes.labelsize: 12
Common Use Cases
Use Case 1: Multiple Line Plots with Legend
import matplotlib.pyplot as plt
import numpy as np
# Generate data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) * np.exp(-x/10)
# Create plot
plt.figure(figsize=(10, 6))
plt.plot(x, y1, 'b-', label='sin(x)', linewidth=2)
plt.plot(x, y2, 'r--', label='cos(x)', linewidth=2)
plt.plot(x, y3, 'g-.', label='damped sin(x)', linewidth=2)
# Customize
plt.xlabel('X axis', fontsize=12)
plt.ylabel('Y axis', fontsize=12)
plt.title('Trigonometric Functions', fontsize=14)
plt.legend(loc='upper right')
plt.grid(True, alpha=0.3)
# Save and display
plt.savefig('trig_functions.png', dpi=300, bbox_inches='tight')
plt.show()
Use Case 2: Subplots with Different Plot Types
import matplotlib.pyplot as plt
import numpy as np
# Generate data
x = np.linspace(0, 10, 50)
y = 2 * x + 1 + np.random.randn(50) * 2
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]
# Create 2x2 subplot grid
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Scatter plot
axes[0, 0].scatter(x, y, alpha=0.6)
axes[0, 0].set_title('Scatter Plot')
axes[0, 0].set_xlabel('X')
axes[0, 0].set_ylabel('Y')
# Line plot
axes[0, 1].plot(x, np.sin(x), 'r-', linewidth=2)
axes[0, 1].set_title('Line Plot')
axes[0, 1].grid(True)
# Bar chart
axes[1, 0].bar(categories, values, color='skyblue', edgecolor='black')
axes[1, 0].set_title('Bar Chart')
axes[1, 0].set_ylabel('Values')
# Histogram
axes[1, 1].hist(y, bins=15, color='green', alpha=0.7, edgecolor='black')
axes[1, 1].set_title('Histogram')
axes[1, 1].set_xlabel('Value')
# Adjust layout and save
plt.tight_layout()
plt.savefig('subplots_example.png', dpi=300)
plt.show()
Use Case 3: Heatmap with Colorbar
import matplotlib.pyplot as plt
import numpy as np
# Generate 2D data
data = np.random.randn(10, 10)
# Create heatmap
fig, ax = plt.subplots(figsize=(8, 6))
im = ax.imshow(data, cmap='RdYlBu_r', aspect='auto')
# Add colorbar
cbar = plt.colorbar(im, ax=ax)
cbar.set_label('Values', rotation=270, labelpad=20)
# Customize ticks
ax.set_xticks(np.arange(10))
ax.set_yticks(np.arange(10))
ax.set_xticklabels([f'Col {i}' for i in range(10)])
ax.set_yticklabels([f'Row {i}' for i in range(10)])
# Rotate x-axis labels
plt.setp(ax.get_xticklabels(), rotation=45, ha='right')
# Add title
ax.set_title('Heatmap Example')
plt.tight_layout()
plt.savefig('heatmap.png', dpi=300, bbox_inches='tight')
plt.show()
Use Case 4: Time Series with Dual Y-Axes
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Generate time series data
dates = pd.date_range('2023-01-01', periods=100)
temperature = 20 + 10 * np.sin(np.linspace(0, 4*np.pi, 100)) + np.random.randn(100)
humidity = 60 + 20 * np.cos(np.linspace(0, 4*np.pi, 100)) + np.random.randn(100) * 5
# Create figure with primary axis
fig, ax1 = plt.subplots(figsize=(12, 6))
# Plot temperature on primary y-axis
color = 'tab:red'
ax1.set_xlabel('Date')
ax1.set_ylabel('Temperature (°C)', color=color)
ax1.plot(dates, temperature, color=color, linewidth=2, label='Temperature')
ax1.tick_params(axis='y', labelcolor=color)
# Create secondary y-axis
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Humidity (%)', color=color)
ax2.plot(dates, humidity, color=color, linewidth=2, linestyle='--', label='Humidity')
ax2.tick_params(axis='y', labelcolor=color)
# Add title and grid
plt.title('Temperature and Humidity Over Time')
ax1.grid(True, alpha=0.3)
# Format x-axis dates
fig.autofmt_xdate()
plt.tight_layout()
plt.savefig('dual_axis_timeseries.png', dpi=300)
plt.show()
Use Case 5: Statistical Visualization with Error Bars
import matplotlib.pyplot as plt
import numpy as np
# Generate data with error
x = np.arange(0, 10, 1)
y = 2 * x + 5
error = np.random.uniform(0.5, 2.0, len(x))
# Create error bar plot
fig, ax = plt.subplots(figsize=(10, 6))
ax.errorbar(x, y, yerr=error, fmt='o-', capsize=5, capthick=2,
ecolor='red', linewidth=2, markersize=8,
label='Measured Data')
# Add fitted line
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
ax.plot(x, p(x), 'g--', linewidth=2, label='Fitted Line')
# Customize
ax.set_xlabel('X Variable', fontsize=12)
ax.set_ylabel('Y Variable', fontsize=12)
ax.set_title('Measurements with Error Bars', fontsize=14)
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('error_bars.png', dpi=300)
plt.show()
Best Practices
- Use Object-Oriented Interface: For complex plots, use
fig, ax = plt.subplots() instead of pyplot state machine for better control and clarity
- Close Figures: Call
plt.close() after saving plots in scripts to free memory, especially when generating many plots
- Set Figure Size Early: Define
figsize when creating figures to ensure proper layout before adding elements
- Use Vectorized Formats: Save publication figures as PDF or SVG (
plt.savefig('plot.pdf')) for scalability and quality
- Leverage Style Sheets: Use
plt.style.use() for consistent styling across multiple plots instead of setting parameters individually
- Label Everything: Always include axis labels, titles, and legends to make plots self-explanatory
- Use Tight Layout: Call
plt.tight_layout() or bbox_inches='tight' when saving to prevent label cutoff
- Choose Appropriate Colormaps: Use perceptually uniform colormaps like ‘viridis’, ‘plasma’, or ‘cividis’ for scientific data
- Optimize DPI: Use
dpi=300 for print quality, dpi=100 for screen display to balance quality and file size
- Batch Processing: When creating multiple plots, wrap in functions and use context managers to ensure proper resource cleanup
Troubleshooting
| Issue | Solution |
|---|
| Plot doesn’t display | Call plt.show() at the end, or check if running in non-interactive environment. Use plt.ion() for interactive mode |
| ”Matplotlib is currently using agg” backend error | Install GUI backend: pip install pyqt5 or set backend: plt.switch_backend('TkAgg') |
| Labels cut off when saving | Use plt.tight_layout() before saving or plt.savefig('file.png', bbox_inches='tight') |
| Memory leak in loop | Call plt.close() or plt.close('all') after each plot to free memory |
| Import error on macOS | Reinstall with framework build: pip uninstall matplotlib && pip install matplotlib or use conda |
| Blurry plots | Increase DPI: plt.savefig('plot.png', dpi=300) or set plt.rcParams['figure.dpi'] = 300 |
| Unicode/LaTeX errors | Disable LaTeX: plt.rcParams['text.usetex'] = False or install LaTeX distribution |
| Slow rendering | Reduce data points, use rasterized=True for large scatter plots, or switch backend |
| Legend overlaps data | Use plt.legend(loc='best') for auto-positioning or bbox_to_anchor for manual placement |
| Subplot spacing issues | Use plt.tight_layout() or manually adjust with plt.subplots_adjust(hspace=0.3, wspace=0.3) |
| Color not changing | Check if using correct parameter name: color or c, ensure color string is valid |