Matplotlib Kit
Battle-tested skill for foundational, plotting, library, create. Includes structured workflows, validation checks, and reusable patterns for scientific.
Matplotlib Kit
Create publication-quality visualizations using matplotlib, Python's foundational plotting library. This skill covers the pyplot interface, object-oriented API, subplot layouts, custom styling, and automated figure generation for data analysis and scientific publishing.
When to Use This Skill
Choose Matplotlib Kit when you need to:
- Create publication-quality static figures with precise control over every element
- Build complex multi-panel figures with shared axes and custom layouts
- Generate standard scientific plots (scatter, line, bar, histogram, heatmap)
- Automate figure generation in data processing pipelines
Consider alternatives when:
- You need interactive web-based visualizations (use Plotly or Bokeh)
- You need statistical visualization with minimal code (use Seaborn, which wraps matplotlib)
- You need real-time updating dashboards (use Dash or Streamlit)
Quick Start
pip install matplotlib numpy pandas
import matplotlib.pyplot as plt import numpy as np # Simple publication-ready figure fig, ax = plt.subplots(figsize=(8, 5)) x = np.linspace(0, 10, 100) ax.plot(x, np.sin(x), label="sin(x)", linewidth=2) ax.plot(x, np.cos(x), label="cos(x)", linewidth=2, linestyle="--") ax.set_xlabel("x", fontsize=12) ax.set_ylabel("f(x)", fontsize=12) ax.set_title("Trigonometric Functions", fontsize=14) ax.legend(fontsize=11) ax.grid(True, alpha=0.3) fig.tight_layout() fig.savefig("trig_functions.png", dpi=300, bbox_inches="tight") plt.show()
Core Concepts
Plot Types
| Function | Plot Type | Best For |
|---|---|---|
ax.plot() | Line plot | Time series, continuous data |
ax.scatter() | Scatter plot | Correlation, distributions |
ax.bar() / ax.barh() | Bar chart | Categorical comparisons |
ax.hist() | Histogram | Frequency distributions |
ax.imshow() | Heatmap/Image | Matrices, correlations |
ax.boxplot() | Box plot | Distribution summaries |
ax.errorbar() | Error bar plot | Measurements with uncertainty |
ax.fill_between() | Filled area | Confidence intervals |
ax.contour() | Contour plot | 2D scalar fields |
ax.quiver() | Vector field | Flow visualization |
Multi-Panel Figures
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import numpy as np # Complex layout with GridSpec fig = plt.figure(figsize=(12, 8)) gs = gridspec.GridSpec(2, 3, hspace=0.35, wspace=0.3) # Large panel spanning two columns ax1 = fig.add_subplot(gs[0, :2]) x = np.linspace(0, 10, 200) ax1.plot(x, np.sin(x) * np.exp(-0.1 * x), "b-", linewidth=2) ax1.set_title("A) Damped Oscillation") ax1.set_xlabel("Time (s)") ax1.set_ylabel("Amplitude") # Small panel ax2 = fig.add_subplot(gs[0, 2]) data = np.random.randn(1000) ax2.hist(data, bins=30, color="#4A90D9", edgecolor="white") ax2.set_title("B) Distribution") # Bottom row panels np.random.seed(42) for i, (title, color) in enumerate([ ("C) Group A", "#E74C3C"), ("D) Group B", "#2ECC71"), ("E) Group C", "#9B59B6") ]): ax = fig.add_subplot(gs[1, i]) y = np.random.randn(50).cumsum() ax.plot(y, color=color, linewidth=1.5) ax.fill_between(range(50), y, alpha=0.2, color=color) ax.set_title(title) fig.savefig("multi_panel.png", dpi=300, bbox_inches="tight")
Custom Styling
import matplotlib.pyplot as plt import matplotlib as mpl # Define a reusable style custom_style = { "figure.figsize": (8, 5), "figure.dpi": 150, "axes.titlesize": 14, "axes.labelsize": 12, "xtick.labelsize": 10, "ytick.labelsize": 10, "legend.fontsize": 10, "lines.linewidth": 2, "axes.spines.top": False, "axes.spines.right": False, "axes.grid": True, "grid.alpha": 0.3, "font.family": "sans-serif", "axes.prop_cycle": mpl.cycler( color=["#4A90D9", "#E74C3C", "#2ECC71", "#F39C12", "#9B59B6", "#1ABC9C", "#E67E22", "#34495E"] ) } # Apply style with plt.rc_context(custom_style): fig, ax = plt.subplots() for i in range(4): ax.plot(range(10), [x * (i + 1) for x in range(10)], label=f"Series {i+1}") ax.legend() ax.set_title("Custom Styled Plot") fig.savefig("styled_plot.png", bbox_inches="tight")
Automated Figure Generation
import matplotlib.pyplot as plt import pandas as pd import numpy as np from pathlib import Path def generate_report_figures(data, output_dir): """Generate a set of standard report figures from a DataFrame.""" output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) numeric_cols = data.select_dtypes(include=[np.number]).columns # 1. Distribution plots for all numeric columns n_cols = len(numeric_cols) fig, axes = plt.subplots(1, n_cols, figsize=(4 * n_cols, 4)) if n_cols == 1: axes = [axes] for ax, col in zip(axes, numeric_cols): data[col].hist(ax=ax, bins=25, color="#4A90D9", edgecolor="white") ax.set_title(col) ax.set_ylabel("Count") fig.tight_layout() fig.savefig(output_dir / "distributions.png", dpi=200) plt.close(fig) # 2. Correlation heatmap if n_cols >= 2: fig, ax = plt.subplots(figsize=(8, 6)) corr = data[numeric_cols].corr() im = ax.imshow(corr, cmap="RdBu_r", vmin=-1, vmax=1) ax.set_xticks(range(n_cols)) ax.set_xticklabels(numeric_cols, rotation=45, ha="right") ax.set_yticks(range(n_cols)) ax.set_yticklabels(numeric_cols) fig.colorbar(im, label="Correlation") ax.set_title("Correlation Matrix") fig.tight_layout() fig.savefig(output_dir / "correlation.png", dpi=200) plt.close(fig) print(f"Saved figures to {output_dir}") # Usage df = pd.DataFrame(np.random.randn(200, 4), columns=["A", "B", "C", "D"]) generate_report_figures(df, "./report_figures")
Configuration
| Parameter | Description | Default |
|---|---|---|
figure.figsize | Figure width and height in inches | (6.4, 4.8) |
figure.dpi | Resolution in dots per inch | 100 |
savefig.dpi | Saved figure resolution | 150 |
font.family | Font family for text | "sans-serif" |
axes.grid | Show grid lines | False |
savefig.format | Default save format | "png" |
Best Practices
-
Use the object-oriented API — Use
fig, ax = plt.subplots()and call methods on theaxobject (ax.plot,ax.set_xlabel) instead ofplt.plot,plt.xlabel. The OO API gives explicit control over which axes you're modifying and avoids state-related bugs in multi-figure scripts. -
Always call
fig.tight_layout()orconstrained_layout=True— Without layout adjustment, axis labels and titles frequently overlap or get clipped. Callfig.tight_layout()before saving, or passconstrained_layout=Truetoplt.subplots()for automatic spacing. -
Save as vector format for publications — Use
fig.savefig("plot.pdf")or.svgfor journal submissions. Vector formats scale without pixelation and most journals prefer them. Use PNG only for web display or when the figure contains many thousands of data points. -
Close figures after saving — Call
plt.close(fig)after saving each figure in loops or scripts that generate many plots. Without closing, matplotlib keeps all figures in memory, which causes memory exhaustion after hundreds of figures. -
Set consistent styling across a project — Create a custom
mplstylefile orrcParamsdictionary and apply it at the start of every script. This ensures all figures in a paper or report have matching fonts, colors, and sizes without duplicating style code.
Common Issues
Axis labels or titles cut off in saved figures — The default figure boundary doesn't account for text outside the axes. Use bbox_inches="tight" in savefig() to automatically expand the boundary, or call fig.tight_layout() before saving.
Fonts not found or falling back to defaults — Matplotlib caches available fonts. After installing new fonts, delete the cache: rm -rf ~/.cache/matplotlib. Then rebuild with matplotlib.font_manager._load_fontmanager(try_read_cache=False). Verify font availability with matplotlib.font_manager.findSystemFonts().
Plots appear blank when running in scripts — Matplotlib defaults to an interactive backend that expects a display. In headless environments (servers, CI), set the backend at the top of your script before any other matplotlib import: import matplotlib; matplotlib.use("Agg"). This switches to the non-interactive Agg backend that renders directly to file.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Full-Stack Code Reviewer
Comprehensive code review skill that checks for security vulnerabilities, performance issues, accessibility, and best practices across frontend and backend code.
Test Suite Generator
Generates comprehensive test suites with unit tests, integration tests, and edge cases. Supports Jest, Vitest, Pytest, and Go testing.
Pro Architecture Workspace
Battle-tested skill for architectural, decision, making, framework. Includes structured workflows, validation checks, and reusable patterns for development.