Matplotlib Introduction
Visualize data in Python with Matplotlib, the foundation for static, animated, and interactive charts.
Why Matplotlib?
Matplotlib is the most widely adopted plotting library in the Python ecosystem. It powers libraries like Pandas, Seaborn, and scikit-learn, giving you granular control over every plot element.
- Generate publication-ready charts with minimal code.
- Customize colors, typography, and layout down to individual axes.
- Export graphics for dashboards, reports, and scientific publications.
Installation
Install Matplotlib within your virtual environment to isolate dependencies. Coordinate version pinning with your team through info.studygrid@gmail.com.
pip install matplotlibMatplotlib automatically picks an appropriate backend for rendering. For headless servers, set the backend explicitly (for example, matplotlib.use("Agg")).
Core Concepts
Matplotlib revolves around figures, axes, and artists:
- Figure: The entire canvas or window.
- Axes: Individual plotting areas within a figure.
- Artists: Visual elements such as lines, text, and patches.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4])
ax.set_title("Quadratic Growth")
plt.show()Workflow Overview
A typical Matplotlib workflow includes:
- Import
matplotlib.pyplotasplt. - Create a figure and axes using
plt.subplots(). - Plot data with axes methods like
plot(),scatter(), orbar(). - Style the chart with labels, titles, and legends.
- Display or save the figure.
Backends Explained
Backends render figures to different targets. Use interactive backends (like QtAgg) for notebooks and desktop apps, and non-interactive backends (like Agg) for automated image generation.
Next Steps
Continue to the getting started guide to configure your environment, understand figure anatomy, and produce your first line chart.
The Two Interfaces
Matplotlib offers two styles. The pyplot (state-machine) style is quick for simple charts; the object-oriented style (explicit fig, ax) scales to complex figures and is preferred for real work.
import matplotlib.pyplot as plt
# pyplot style
plt.plot([1, 2, 3], [2, 4, 1])
plt.title("Quick")
plt.show()
# object-oriented style (recommended)
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 4, 1])
ax.set_title("Explicit")
plt.show()Save a figure to a file instead of showing it with plt.savefig("chart.png", dpi=150, bbox_inches="tight").
Try It Yourself
Exercise: Plot the points (1,1), (2,4), (3,9) and give the chart a title.
Show solution
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("Squares")
plt.show()Key Takeaways
- Matplotlib is Python's foundational plotting library.
- Prefer the object-oriented
fig, axstyle for anything non-trivial. - Use
savefigto export charts.
📘 Real-World Deep Dive
matplotlib is the workhorse 2-D plotting library of Python — verbose but flexible. The patterns you'll use 80% of the time: <code>plt.subplots</code>, <code>ax.plot/ax.scatter/ax.hist</code>, and a small set of formatter tricks.
Real-Life Scenario
A marketing-style report: a 1×3 figure showing distribution, time series, and category totals — saved to disk for a static report.
Real-Life Example
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(7)
fig, axes = plt.subplots(1, 3, figsize=(11, 3.2))
# 1) Histogram of a sample
samples = rng.normal(loc=50, scale=8, size=2_000)
axes[0].hist(samples, bins=30, color="#3b82f6", edgecolor="white")
axes[0].set_title("Distribution of n = 2000 samples")
# 2) Time series with a trend line
t = np.arange(0, 365)
y = 100 + 0.3*t + rng.normal(0, 5, size=365)
axes[1].plot(t, y, color="#0d9488", linewidth=1.5)
z = np.polyfit(t, y, 1)
axes[1].plot(t, z[0]*t + z[1], "--", color="#ef4444", label="trend")
axes[1].legend()
axes[1].set_title("Activity over the year")
# 3) Grouped bars
labels = ["starter", "pro", "enterprise"]
counts = [1240, 380, 95]
axes[2].bar(labels, counts, color=["#22c55e", "#3b82f6", "#a855f7"])
axes[2].set_title("Plan distribution")
fig.suptitle("Quarterly metrics", fontsize=14)
fig.tight_layout()
fig.savefig("quarterly.png", dpi=150, bbox_inches="tight")
print("wrote quarterly.png")Expected Output
wrote quarterly.pngCommon mistakes
- Calling
plt.show()inside a non-interactive script produces no output — callplt.savefig(...)instead. - Mixing
numpy.datetime64with Pythondatetime.datemis-axes — cast at the boundary. np.random.seed(0)is the legacy global RNG; prefernp.random.default_rng(0)for reproducible scripts.
🚀 Performance & Best Practices
- Set
matplotlib.use("Agg")at import time on web servers to avoid GPU contention. - For tens of thousands of points, switch to
datashader+bokeh. - Cache figure objects across calls — Matplotlib's biggest cost is construction, not drawing.
🧪 Try It Yourself
- Add a legend that explains the colour palette of the bars.
- Render the same 1×3 grid using
plotly.subplotsand compare file sizes. - Move the
fig.savefiginto amake_report(rows) -> Pathfactory.