When to Use
Use this skill when:
- Creating any type of plot or chart (line, scatter, bar, histogram, heatmap, contour, box, violin, 3D surface, etc.)
- Generating scientific or statistical visualizations
- Customizing plot appearance (colors, styles, labels, legends, annotations)
- Creating multi-panel figures with subplots, mosaic layouts, or GridSpec
- Exporting visualizations to PNG, PDF, SVG, or other formats
- Building interactive plots or animations
- Working with 3D visualizations
- Integrating plots into Jupyter notebooks or GUI applications
Trigger keywords: plot, chart, figure, axes, subplot, matplotlib, pyplot, visualization, heatmap, contour, histogram, scatter, bar chart, savefig, rcParams, colormap.
Prerequisites
- Python 3.8+ installed and available on
PATH
- Matplotlib installed:
pip install matplotlib (NumPy is a required dependency and installs automatically)
- For Jupyter integration:
pip install jupyter and run %matplotlib inline or %matplotlib widget in a notebook cell
- Windows host is primary (PowerShell). Use
python (not python3) in PowerShell commands.
Procedure
1. Choose the Interface
Object-Oriented (RECOMMENDED for all production code):
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])
ax.set_ylabel('some numbers')
plt.show()
- Explicit control over Figure and Axes objects
- Better for complex figures with multiple subplots
- Easier to maintain and debug
pyplot (MATLAB-style — quick exploration only):
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
- Stateful; convenient for simple scripts
- Avoid in production code due to implicit state confusion
2. Create a Basic Plot (OO Interface)
import matplotlib.pyplot as plt
import numpy as np
# Create figure and axes with explicit size
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
# Generate and plot data
x = np.linspace(0, 2*np.pi, 100)
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')
# Customize
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Trigonometric Functions')
ax.legend()
ax.grid(True, alpha=0.3)
# Save and/or display
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
plt.show()
3. Create Multi-Panel Figures
Regular grid:
fig, axes = plt.subplots(2, 2, figsize=(12, 10), constrained_layout=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)
Mosaic layout (flexible, label-based):
fig, axes = plt.subplot_mosaic([['left', 'right_top'],
['left', 'right_bottom']],
figsize=(10, 8))
axes['left'].plot(x, y)
axes['right_top'].scatter(x, y)
axes['right_bottom'].hist(data)
GridSpec (maximum control):
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(12, 8))
gs = GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :]) # Top row, all columns
ax2 = fig.add_subplot(gs[1:, 0]) # Bottom two rows, first column
ax3 = fig.add_subplot(gs[1:, 1:]) # Bottom two rows, last two columns
4. Select Plot Types
| Plot Type |
Use Case |
Example Call |
| Line |
Time series, trends |
ax.plot(x, y, linewidth=2, linestyle='--', marker='o', color='blue') |
| Scatter |
Correlations |
ax.scatter(x, y, s=sizes, c=colors, alpha=0.6, cmap='viridis') |
| Bar |
Categorical comparisons |
ax.bar(categories, values, color='steelblue', edgecolor='black') |
| Horizontal bar |
Long labels |
ax.barh(categories, values) |
| Histogram |
Distributions |
ax.hist(data, bins=30, edgecolor='black', alpha=0.7) |
| Heatmap |
Matrix data |
im = ax.imshow(matrix, cmap='coolwarm', aspect='auto') then plt.colorbar(im, ax=ax) |
| Contour |
3D data on 2D |
contour = ax.contour(X, Y, Z, levels=10) then ax.clabel(contour, inline=True, fontsize=8) |
| Box |
Statistical distributions |
ax.boxplot([data1, data2, data3], labels=['A', 'B', 'C']) |
| Violin |
Distribution densities |
ax.violinplot([data1, data2, data3], positions=[1, 2, 3]) |
For specialized plot types beyond the table, use the official gallery: https://matplotlib.org/stable/gallery/index.html
5. Apply Styling and Customization
Color specification methods:
- Named colors:
'red', 'blue', 'steelblue'
- Hex codes:
'#FF5733'
- RGB tuples:
(0.1, 0.2, 0.3)
- Colormaps:
cmap='viridis', cmap='plasma', cmap='coolwarm'
Style sheets:
plt.style.use('seaborn-v0_8-darkgrid')
print(plt.style.available) # List all available styles
# Common: 'ggplot', 'bmh', 'fivethirtyeight', 'seaborn-v0_8-darkgrid'
rcParams for global defaults:
plt.rcParams['font.size'] = 12
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['axes.titlesize'] = 16
plt.rcParams['xtick.labelsize'] = 10
plt.rcParams['ytick.labelsize'] = 10
plt.rcParams['legend.fontsize'] = 12
plt.rcParams['figure.titlesize'] = 18
Text and annotations:
ax.text(x, y, 'annotation', fontsize=12, ha='center')
ax.annotate('important point', xy=(x, y), xytext=(x+1, y+1),
arrowprops=dict(arrowstyle='->', color='red'))
For colormap and style-sheet options, prefer perceptually uniform maps (viridis, plasma, cividis) and the official cheatsheets: https://matplotlib.org/cheatsheets/
6. Save and Export Figures
# High-resolution PNG for presentations/papers
plt.savefig('figure.png', dpi=300, bbox_inches='tight', facecolor='white')
# Vector format for publications (scalable)
plt.savefig('figure.pdf', bbox_inches='tight')
plt.savefig('figure.svg', bbox_inches='tight')
# Transparent background
plt.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)
Key parameters:
| Parameter |
Purpose |
Recommended Value |
dpi |
Resolution |
300 for publications, 150 for web, 72 for screen |
bbox_inches='tight' |
Remove excess whitespace |
Always use |
facecolor='white' |
Ensure white background |
Use with dark themes |
transparent=True |
Transparent background |
For overlays |
7. Create 3D Plots
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# Surface plot
ax.plot_surface(X, Y, Z, cmap='viridis')
# 3D scatter
ax.scatter(x, y, z, c=colors, marker='o')
# 3D line plot
ax.plot(x, y, z, linewidth=2)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
8. Confirm Unfamiliar APIs
Look up method signatures on the Matplotlib API index (https://matplotlib.org/stable/api/index.html) rather than guessing Axes/Figure parameters. Gallery examples at https://matplotlib.org/stable/gallery/index.html cover specialized plot types.
9. Organize Reusable Plot Code
def create_analysis_plot(data, title):
"""Create standardized analysis plot."""
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
ax.plot(data['x'], data['y'], linewidth=2)
ax.set_xlabel('X Axis Label', fontsize=12)
ax.set_ylabel('Y Axis Label', fontsize=12)
ax.set_title(title, fontsize=14, fontweight='bold')
ax.grid(True, alpha=0.3)
return fig, ax
fig, ax = create_analysis_plot(my_data, 'My Analysis')
plt.savefig('analysis.png', dpi=300, bbox_inches='tight')
Pitfalls
- Overlapping elements — Use
constrained_layout=True at figure creation or call fig.tight_layout() before saving. Do not use both together.
- State confusion with pyplot interface — The pyplot state machine tracks the "current" figure/axes implicitly. Use the OO interface (
fig, ax = plt.subplots()) to avoid ambiguity in production code.
- Memory leaks with many figures — Always close figures explicitly with
plt.close(fig) when generating many plots in a loop. Unclosed figures accumulate in memory.
- Font warnings — If fonts are missing, suppress warnings by setting
plt.rcParams['font.sans-serif'] = ['DejaVu Sans'] or install the required font package.
- DPI confusion —
figsize is in inches, not pixels. Final pixel dimensions: pixels = dpi * inches. A (10, 6) figure at 300 dpi produces a 3000×1800 image.
- Rainbow colormaps (jet) — Not perceptually uniform; can misrepresent data. Use
viridis, plasma, inferno, or cividis instead.
- Large dataset file size — For scatter/line plots with many points, pass
rasterized=True to reduce PDF/SVG file size. Downsample dense time series before plotting.
show() blocks in scripts — plt.show() blocks execution in non-interactive scripts. Call savefig() before show() to ensure the file is written.
- Style name changes — Seaborn styles were renamed in matplotlib 3.6+ (e.g.,
'seaborn-darkgrid' → 'seaborn-v0_8-darkgrid'). Use plt.style.available to check valid names.
Verification
Check Installation
python -c "import matplotlib; print(matplotlib.__version__)"
Expected output (version may differ):
3.9.0
Verify a Plot Renders and Saves
python -c "import matplotlib.pyplot as plt; fig, ax = plt.subplots(); ax.plot([1,2,3,4]); plt.savefig('test_plot.png', dpi=150, bbox_inches='tight'); print('OK')"
Expected output:
OK
Verify the file exists:
Test-Path .\test_plot.png
Expected output:
True
Verify Available Styles
python -c "import matplotlib.pyplot as plt; print(plt.style.available)"
Verify Backend (Non-Interactive / Headless)
python -c "import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt; print(matplotlib.get_backend())"
Expected output:
Agg
Related Skills
- numpy — Array generation and numerical data feeding into plots
- pandas — DataFrame-based plotting and data manipulation
- seaborn — High-level statistical visualizations built on matplotlib
Additional Resources
Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
1---
2name: matplotlib
3description: "Builds Matplotlib figures with the OO Axes API: subplots, mosaic, GridSpec, rcParams, and savefig to PNG/PDF/SVG. Use for pyplot line, scatter, bar, hist, heatmap, contour, or 3D work in Python. Never route Seaborn estimators or Plotly Dash apps through this chair."
4version: 1.0.1
5license: https://github.com/matplotlib/matplotlib/tree/main/LICENSE
6metadata:
7 source: https://skillmd.com/skills/kayforkind/matplotlib
8 skill-author: K-Dense Inc.
9risk: unknown
10source: community
11---
12
13## When to Use
14
15Use this skill when:
16
17- Creating any type of plot or chart (line, scatter, bar, histogram, heatmap, contour, box, violin, 3D surface, etc.)
18- Generating scientific or statistical visualizations
19- Customizing plot appearance (colors, styles, labels, legends, annotations)
20- Creating multi-panel figures with subplots, mosaic layouts, or GridSpec
21- Exporting visualizations to PNG, PDF, SVG, or other formats
22- Building interactive plots or animations
23- Working with 3D visualizations
24- Integrating plots into Jupyter notebooks or GUI applications
25
26**Trigger keywords:** plot, chart, figure, axes, subplot, matplotlib, pyplot, visualization, heatmap, contour, histogram, scatter, bar chart, savefig, rcParams, colormap.
27
28## Prerequisites
29
30- Python 3.8+ installed and available on `PATH`
31- Matplotlib installed: `pip install matplotlib` (NumPy is a required dependency and installs automatically)
32- For Jupyter integration: `pip install jupyter` and run `%matplotlib inline` or `%matplotlib widget` in a notebook cell
33- Windows host is primary (PowerShell). Use `python` (not `python3`) in PowerShell commands.
34
35## Procedure
36
37### 1. Choose the Interface
38
39**Object-Oriented (RECOMMENDED for all production code):**
40
41```python
42import matplotlib.pyplot as plt
43
44fig, ax = plt.subplots()
45ax.plot([1, 2, 3, 4])
46ax.set_ylabel('some numbers')
47plt.show()
48```
49
50- Explicit control over Figure and Axes objects
51- Better for complex figures with multiple subplots
52- Easier to maintain and debug
53
54**pyplot (MATLAB-style — quick exploration only):**
55
56```python
57import matplotlib.pyplot as plt
58
59plt.plot([1, 2, 3, 4])
60plt.ylabel('some numbers')
61plt.show()
62```
63
64- Stateful; convenient for simple scripts
65- Avoid in production code due to implicit state confusion
66
67### 2. Create a Basic Plot (OO Interface)
68
69```python
70import matplotlib.pyplot as plt
71import numpy as np
72
73# Create figure and axes with explicit size
74fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
75
76# Generate and plot data
77x = np.linspace(0, 2*np.pi, 100)
78ax.plot(x, np.sin(x), label='sin(x)')
79ax.plot(x, np.cos(x), label='cos(x)')
80
81# Customize
82ax.set_xlabel('x')
83ax.set_ylabel('y')
84ax.set_title('Trigonometric Functions')
85ax.legend()
86ax.grid(True, alpha=0.3)
87
88# Save and/or display
89plt.savefig('plot.png', dpi=300, bbox_inches='tight')
90plt.show()
91```
92
93### 3. Create Multi-Panel Figures
94
95**Regular grid:**
96
97```python
98fig, axes = plt.subplots(2, 2, figsize=(12, 10), constrained_layout=True)
99axes[0, 0].plot(x, y1)
100axes[0, 1].scatter(x, y2)
101axes[1, 0].bar(categories, values)
102axes[1, 1].hist(data, bins=30)
103```
104
105**Mosaic layout (flexible, label-based):**
106
107```python
108fig, axes = plt.subplot_mosaic([['left', 'right_top'],
109 ['left', 'right_bottom']],
110 figsize=(10, 8))
111axes['left'].plot(x, y)
112axes['right_top'].scatter(x, y)
113axes['right_bottom'].hist(data)
114```
115
116**GridSpec (maximum control):**
117
118```python
119from matplotlib.gridspec import GridSpec
120
121fig = plt.figure(figsize=(12, 8))
122gs = GridSpec(3, 3, figure=fig)
123ax1 = fig.add_subplot(gs[0, :]) # Top row, all columns
124ax2 = fig.add_subplot(gs[1:, 0]) # Bottom two rows, first column
125ax3 = fig.add_subplot(gs[1:, 1:]) # Bottom two rows, last two columns
126```
127
128### 4. Select Plot Types
129
130| Plot Type | Use Case | Example Call |
131|-----------|----------|--------------|
132| Line | Time series, trends | `ax.plot(x, y, linewidth=2, linestyle='--', marker='o', color='blue')` |
133| Scatter | Correlations | `ax.scatter(x, y, s=sizes, c=colors, alpha=0.6, cmap='viridis')` |
134| Bar | Categorical comparisons | `ax.bar(categories, values, color='steelblue', edgecolor='black')` |
135| Horizontal bar | Long labels | `ax.barh(categories, values)` |
136| Histogram | Distributions | `ax.hist(data, bins=30, edgecolor='black', alpha=0.7)` |
137| Heatmap | Matrix data | `im = ax.imshow(matrix, cmap='coolwarm', aspect='auto')` then `plt.colorbar(im, ax=ax)` |
138| Contour | 3D data on 2D | `contour = ax.contour(X, Y, Z, levels=10)` then `ax.clabel(contour, inline=True, fontsize=8)` |
139| Box | Statistical distributions | `ax.boxplot([data1, data2, data3], labels=['A', 'B', 'C'])` |
140| Violin | Distribution densities | `ax.violinplot([data1, data2, data3], positions=[1, 2, 3])` |
141
142For specialized plot types beyond the table, use the official gallery: https://matplotlib.org/stable/gallery/index.html
143
144### 5. Apply Styling and Customization
145
146**Color specification methods:**
147
148- Named colors: `'red'`, `'blue'`, `'steelblue'`
149- Hex codes: `'#FF5733'`
150- RGB tuples: `(0.1, 0.2, 0.3)`
151- Colormaps: `cmap='viridis'`, `cmap='plasma'`, `cmap='coolwarm'`
152
153**Style sheets:**
154
155```python
156plt.style.use('seaborn-v0_8-darkgrid')
157print(plt.style.available) # List all available styles
158# Common: 'ggplot', 'bmh', 'fivethirtyeight', 'seaborn-v0_8-darkgrid'
159```
160
161**rcParams for global defaults:**
162
163```python
164plt.rcParams['font.size'] = 12
165plt.rcParams['axes.labelsize'] = 14
166plt.rcParams['axes.titlesize'] = 16
167plt.rcParams['xtick.labelsize'] = 10
168plt.rcParams['ytick.labelsize'] = 10
169plt.rcParams['legend.fontsize'] = 12
170plt.rcParams['figure.titlesize'] = 18
171```
172
173**Text and annotations:**
174
175```python
176ax.text(x, y, 'annotation', fontsize=12, ha='center')
177ax.annotate('important point', xy=(x, y), xytext=(x+1, y+1),
178 arrowprops=dict(arrowstyle='->', color='red'))
179```
180
181For colormap and style-sheet options, prefer perceptually uniform maps (`viridis`, `plasma`, `cividis`) and the official cheatsheets: https://matplotlib.org/cheatsheets/
182
183### 6. Save and Export Figures
184
185```python
186# High-resolution PNG for presentations/papers
187plt.savefig('figure.png', dpi=300, bbox_inches='tight', facecolor='white')
188
189# Vector format for publications (scalable)
190plt.savefig('figure.pdf', bbox_inches='tight')
191plt.savefig('figure.svg', bbox_inches='tight')
192
193# Transparent background
194plt.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)
195```
196
197**Key parameters:**
198
199| Parameter | Purpose | Recommended Value |
200|-----------|---------|-------------------|
201| `dpi` | Resolution | 300 for publications, 150 for web, 72 for screen |
202| `bbox_inches='tight'` | Remove excess whitespace | Always use |
203| `facecolor='white'` | Ensure white background | Use with dark themes |
204| `transparent=True` | Transparent background | For overlays |
205
206### 7. Create 3D Plots
207
208```python
209from mpl_toolkits.mplot3d import Axes3D
210
211fig = plt.figure(figsize=(10, 8))
212ax = fig.add_subplot(111, projection='3d')
213
214# Surface plot
215ax.plot_surface(X, Y, Z, cmap='viridis')
216
217# 3D scatter
218ax.scatter(x, y, z, c=colors, marker='o')
219
220# 3D line plot
221ax.plot(x, y, z, linewidth=2)
222
223ax.set_xlabel('X Label')
224ax.set_ylabel('Y Label')
225ax.set_zlabel('Z Label')
226```
227
228### 8. Confirm Unfamiliar APIs
229
230Look up method signatures on the Matplotlib API index (https://matplotlib.org/stable/api/index.html) rather than guessing `Axes`/`Figure` parameters. Gallery examples at https://matplotlib.org/stable/gallery/index.html cover specialized plot types.
231
232### 9. Organize Reusable Plot Code
233
234```python
235def create_analysis_plot(data, title):
236 """Create standardized analysis plot."""
237 fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
238
239 ax.plot(data['x'], data['y'], linewidth=2)
240
241 ax.set_xlabel('X Axis Label', fontsize=12)
242 ax.set_ylabel('Y Axis Label', fontsize=12)
243 ax.set_title(title, fontsize=14, fontweight='bold')
244 ax.grid(True, alpha=0.3)
245
246 return fig, ax
247
248fig, ax = create_analysis_plot(my_data, 'My Analysis')
249plt.savefig('analysis.png', dpi=300, bbox_inches='tight')
250```
251
252## Pitfalls
253
2541. **Overlapping elements** — Use `constrained_layout=True` at figure creation or call `fig.tight_layout()` before saving. Do not use both together.
2552. **State confusion with pyplot interface** — The pyplot state machine tracks the "current" figure/axes implicitly. Use the OO interface (`fig, ax = plt.subplots()`) to avoid ambiguity in production code.
2563. **Memory leaks with many figures** — Always close figures explicitly with `plt.close(fig)` when generating many plots in a loop. Unclosed figures accumulate in memory.
2574. **Font warnings** — If fonts are missing, suppress warnings by setting `plt.rcParams['font.sans-serif'] = ['DejaVu Sans']` or install the required font package.
2585. **DPI confusion** — `figsize` is in inches, not pixels. Final pixel dimensions: `pixels = dpi * inches`. A `(10, 6)` figure at 300 dpi produces a 3000×1800 image.
2596. **Rainbow colormaps (jet)** — Not perceptually uniform; can misrepresent data. Use `viridis`, `plasma`, `inferno`, or `cividis` instead.
2607. **Large dataset file size** — For scatter/line plots with many points, pass `rasterized=True` to reduce PDF/SVG file size. Downsample dense time series before plotting.
2618. **`show()` blocks in scripts** — `plt.show()` blocks execution in non-interactive scripts. Call `savefig()` before `show()` to ensure the file is written.
2629. **Style name changes** — Seaborn styles were renamed in matplotlib 3.6+ (e.g., `'seaborn-darkgrid'` → `'seaborn-v0_8-darkgrid'`). Use `plt.style.available` to check valid names.
263
264## Verification
265
266### Check Installation
267
268```powershell
269python -c "import matplotlib; print(matplotlib.__version__)"
270```
271
272Expected output (version may differ):
273
274```
2753.9.0
276```
277
278### Verify a Plot Renders and Saves
279
280```powershell
281python -c "import matplotlib.pyplot as plt; fig, ax = plt.subplots(); ax.plot([1,2,3,4]); plt.savefig('test_plot.png', dpi=150, bbox_inches='tight'); print('OK')"
282```
283
284Expected output:
285
286```
287OK
288```
289
290Verify the file exists:
291
292```powershell
293Test-Path .\test_plot.png
294```
295
296Expected output:
297
298```
299True
300```
301
302### Verify Available Styles
303
304```powershell
305python -c "import matplotlib.pyplot as plt; print(plt.style.available)"
306```
307
308### Verify Backend (Non-Interactive / Headless)
309
310```powershell
311python -c "import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt; print(matplotlib.get_backend())"
312```
313
314Expected output:
315
316```
317Agg
318```
319
320## Related Skills
321
322- **numpy** — Array generation and numerical data feeding into plots
323- **pandas** — DataFrame-based plotting and data manipulation
324- **seaborn** — High-level statistical visualizations built on matplotlib
325
326## Additional Resources
327
328- Official documentation: https://matplotlib.org/
329- Gallery: https://matplotlib.org/stable/gallery/index.html
330- Cheatsheets: https://matplotlib.org/cheatsheets/
331- Tutorials: https://matplotlib.org/stable/tutorials/index.html
332
333## Limitations
334
335- Use this skill only when the task clearly matches the scope described above.
336- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
337- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.