Builds plots with the matplotlib Python library (pyplot and object-oriented Figure/Axes API) for full low-level customization, exporting to PNG/PDF/SVG. Use when fine-grained control over individual plot elements is needed.
Ships in alterlab-visualization. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Matplotlib is Python's foundational visualization library for creating static, animated, and interactive plots. This skill provides guidance on using matplotlib effectively, covering both the pyplot interface (MATLAB-style) and the object-oriented API (Figure/Axes), along with best practices for creating publication-quality visualizations.
This skill should be used when:
| Scenario | Use Instead |
|---|---|
| Quick statistical plot straight from a DataFrame (box/violin/pair/regression plots with automatic CIs) | alterlab-seaborn |
| Interactive chart with hover/zoom, standalone HTML, or a Dash dashboard | alterlab-plotly |
| Journal-ready figure: column widths, Okabe-Ito palette, panel labels, significance stars | alterlab-scientific-viz |
| Proofing a finished figure for overlapping or clipped labels and 300-dpi export | alterlab-figure-qa |
| Flowchart, pathway, or architecture diagram rather than a plot of data | alterlab-scientific-schematics |
Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-seaborn) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.
Matplotlib uses a hierarchical structure of objects:
1. pyplot Interface (Implicit, MATLAB-style)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
2. Object-Oriented Interface (Explicit)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])
ax.set_ylabel('some numbers')
plt.show()
Single plot workflow:
import matplotlib.pyplot as plt
import numpy as np
# Create figure and axes (OO interface - RECOMMENDED)
fig, ax = plt.subplots(figsize=(10, 6))
# 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()
Creating subplot layouts:
# Method 1: Regular grid
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
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)
# Method 2: Mosaic layout (more flexible)
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)
# Method 3: 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
Line plots - Time series, continuous data, trends
ax.plot(x, y, linewidth=2, linestyle='--', marker='o', color='blue')
Scatter plots - Relationships between variables, correlations
ax.scatter(x, y, s=sizes, c=colors, alpha=0.6, cmap='viridis')
Bar charts - Categorical comparisons
ax.bar(categories, values, color='steelblue', edgecolor='black')
# For horizontal bars:
ax.barh(categories, values)
Histograms - Distributions
ax.hist(data, bins=30, edgecolor='black', alpha=0.7)
Heatmaps - Matrix data, correlations
im = ax.imshow(matrix, cmap='coolwarm', aspect='auto')
plt.colorbar(im, ax=ax)
Contour plots - 3D data on 2D plane
contour = ax.contour(X, Y, Z, levels=10)
ax.clabel(contour, inline=True, fontsize=8)
Box plots - Statistical distributions
# 'tick_labels' replaced 'labels' in matplotlib 3.9 (old name removed in 3.11)
ax.boxplot([data1, data2, data3], tick_labels=['A', 'B', 'C'])
Violin plots - Distribution densities
ax.violinplot([data1, data2, data3], positions=[1, 2, 3])
For comprehensive plot type examples and variations, refer to references/plot_types.md.
Color specification methods:
'red', 'blue', 'steelblue''#FF5733'(0.1, 0.2, 0.3)cmap='viridis', cmap='plasma', cmap='coolwarm'Using style sheets:
plt.style.use('seaborn-v0_8-darkgrid') # Apply predefined style
# Available styles: 'ggplot', 'bmh', 'fivethirtyeight', etc.
print(plt.style.available) # List all available styles
Customizing with rcParams:
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 detailed styling options and colormap guidelines, see references/styling_guide.md.
Export to various formats:
# 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)
Important parameters:
dpi: Resolution (300 for publications, 150 for web, 72 for screen)bbox_inches='tight': Removes excess whitespacefacecolor='white': Ensures white background (useful for transparent themes)transparent=True: Transparent backgroundReporting the result: when the figure or style lives in a script or module, the reply still shows the key code — the plt.style.use(...) / rcParams settings, the fig, ax = plt.subplots(...) call, the plotting call and the savefig(...) arguments — and the path of every file written. A prose summary of the figure does not let the user reuse or check the settings.
# projection='3d' auto-registers the 3D axes; no Axes3D import needed
# (the old `from mpl_toolkits.mplot3d import Axes3D` is a no-op on modern matplotlib).
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)
# Labels
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
fig, ax = plt.subplots(figsize=(10, 6))constrained_layout=True or tight_layout() to prevent overlapping elementsfig, ax = plt.subplots(constrained_layout=True) is recommended for automatic spacingrasterized=True in plot calls to reduce file size# Good practice: Clear structure
def create_analysis_plot(data, title):
"""Create standardized analysis plot."""
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
# Plot data
ax.plot(data['x'], data['y'], linewidth=2)
# Customize
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
# Use the function
fig, ax = create_analysis_plot(my_data, 'My Analysis')
plt.savefig('analysis.png', dpi=300, bbox_inches='tight')
This skill includes runnable helper scripts in the scripts/ directory. Run them
directly to produce a figure or a style sheet, or read them as worked examples of
the patterns above. They require matplotlib>=3.9 and numpy (the histogram
example also needs scipy).
plot_template.pyRun scripts/plot_template.py to render any of the supported plot types (line,
scatter, bar, histogram, heatmap, contour, box, violin, 3d, or all as a GridSpec
montage). Each create_* helper accepts an optional ax= so you can compose your
own multi-panel layouts.
# Render the full montage at 300 DPI
python scripts/plot_template.py --plot-type all --output figure.png
# Single plot type
python scripts/plot_template.py --plot-type scatter --output scatter.png
style_configurator.pyRun scripts/style_configurator.py to preview a style preset (publication,
presentation, web, dark, minimal) and export it as a reusable .mplstyle file.
python scripts/style_configurator.py --list # show presets
python scripts/style_configurator.py --preset publication \
--output my_style.mplstyle # export style sheet
python scripts/style_configurator.py --preset publication --preview
For comprehensive information, consult the reference documents:
references/plot_types.md - Complete catalog of plot types with code examples and use casesreferences/styling_guide.md - Detailed styling options, colormaps, and customizationreferences/api_reference.md - Core classes and methods referencereferences/common_issues.md - Troubleshooting guide for common problemsMatplotlib integrates well with:
%matplotlib inline or %matplotlib widgetconstrained_layout=True or tight_layout()plt.close(fig)plt.rcParams['font.sans-serif']pixels = dpi * inchesplt.subplots(num=1) or plt.subplot_mosaic(..., num=1) raises ValueError if figure 1 exists — pass clear=True, or add axes with fig.subplots() / fig.subplot_mosaic().matplotlib.cm.get_cmap (use matplotlib.colormaps[name]), plot_date (call plot with datetime values), and boxplot labels= (use tick_labels=).vert): vert= on boxplot/violinplot (use orientation='horizontal', available since 3.10), clabel on contourf output (overlay contour lines and label those), and in-place Colormap.set_bad/set_under/set_over (use cmap.with_extremes(bad=..., under=..., over=...)).evals/evals.json (opens in a new tab)references/api_reference.md (opens in a new tab)references/common_issues.md (opens in a new tab)references/plot_types.md (opens in a new tab)references/styling_guide.md (opens in a new tab)scripts/plot_template.py (opens in a new tab)scripts/style_configurator.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
9 skills in this plugin
/alterlab-figure-qaVerify publication figures with a render-then-check QA pass — data-fidelity against every underlying row, axis/label floor-and-ceiling legibility, bounding-box collision detection for overlapping text/markers, and 300-dpi print-readiness. Use when proofing or auditing a finished figure for correctness and print quality, catching mislabeled or overlapping elements, or confirming a plot faithfully represents its data before submission. For CREATING the plot prefer alterlab-matplotlib (or alterlab-seaborn / alterlab-plotly); for multi-panel publication layout prefer alterlab-scientific-viz; for schematic diagrams prefer alterlab-scientific-schematics. Part of the AlterLab Academic Skills suite./alterlab-generate-imageCreates and edits images for research communication with no API key — Claude draws illustrations, concept art, icons, backgrounds and slide/poster visuals as code (SVG, TikZ, matplotlib) rendered locally with exact, editable text, and edits existing images with Pillow (crop, annotate, scale bars, redaction, overlays). Photorealistic generation and AI edits (FLUX.2, Gemini 3.1 Flash Image via OpenRouter) are an optional extra with OPENROUTER_API_KEY. Use when the request is to generate or edit a photo, illustration, artwork, concept art, poster hero image, or presentation/slide visual asset — anything that is not a technical diagram, an infographic, or a data chart. For flowcharts, circuits, pathways, neural-net architectures, and technical/methodology diagrams use alterlab-scientific-schematics; for infographics that lay out statistics or timelines use alterlab-infographics; for plotting numeric data (scatter, bar, line) use alterlab-matplotlib instead. Part of the AlterLab Academic Skills suite./alterlab-infographicsCreates professional infographics with no API key: Claude lays the graphic out as code (SVG, with charts computed from the numbers), renders it locally to PNG/PDF with every word and figure exact, sources statistics with web search when asked, each tied to a citation, then reviews the render itself against a document-type quality threshold and iterates — 10 infographic types, 8 industry styles, colorblind-safe palettes. Optional AI raster generation (Nano Banana Pro, Gemini review, Perplexity research via OpenRouter) with OPENROUTER_API_KEY. Use when the request is for an infographic, data-story graphic, statistical poster, comparison chart, timeline, process/how-to visual, or list/social graphic that pairs a designed layout with figures. Use alterlab-scientific-schematics instead for technical flowcharts, CONSORT/PRISMA, pathways, or architecture diagrams; alterlab-generate-image for non-infographic illustrations; alterlab-matplotlib for exact plots of a dataset. Part of the AlterLab Academic Skills suite./alterlab-mermaidWrites Markdown documents and text-based Mermaid diagrams (flowcharts, sequence, class, ER, gantt, state, and more) with full style guides, 24 diagram-type references, and 9 document templates. Use when a diagram or technical document should live as version-controllable Markdown/Mermaid text rather than a rendered image — READMEs, methods and pipeline diagrams, analysis or status reports, ADRs, and project docs that render natively on GitHub and GitLab. For AI-rendered publication schematics use alterlab-scientific-schematics; for manuscript prose use alterlab-scientific-writing; for plots of numeric data use alterlab-matplotlib. Part of the AlterLab Academic Skills suite./alterlab-plotlyBuilds INTERACTIVE charts with the Plotly Python library (plotly.express / graph_objects) — hover tooltips, zoom/pan, animations, rangesliders, 3D rotation, and standalone HTML/web-embeddable output. Use when a chart must be interactive or web-embedded, for dashboards (incl. Dash), exploratory data analysis, or rotatable 3D plots. For static publication figures defer to alterlab-matplotlib (or alterlab-scientific-viz for journal formatting); for static statistical charts (heatmaps, distributions) defer to alterlab-seaborn; for diagrams/schematics defer to alterlab-scientific-schematics or alterlab-mermaid. Part of the AlterLab Academic Skills suite./alterlab-scientific-schematicsCreates publication-quality scientific diagrams with no API key - Claude draws the diagram as code (SVG, TikZ/PGF, schemdraw for circuits), renders it locally to PNG/PDF with exact, editable labels, then reviews the render itself against a document-type quality threshold (journal 8.5/10, poster 7.0, ...) and revises until it passes (max 2 iterations). Use when the request is for a rendered technical or scientific diagram — CONSORT/PRISMA flowcharts, neural-network architectures, system/block diagrams, biological pathways, circuits, or other complex scientific visuals. Optional AI raster generation (Nano Banana 2 with Gemini review, via OpenRouter) when OPENROUTER_API_KEY is set. For general photos, illustrations, or artwork use alterlab-generate-image; for infographics use alterlab-infographics; for editable text-based Mermaid diagrams use alterlab-mermaid. Part of the AlterLab Academic Skills suite./alterlab-visualization:alterlab-matplotlibfrom alterlab-visualization
npx claudepluginhub alterlab-ieu/alterlab-academic-skills --plugin alterlab-visualization2 plugins in one repository ship this exact skill · first indexed Nov 9, 2026
Other plugins' skills for the same job