Matplotlib Pyplot
Leverage the stateful Pyplot API for rapid plotting while understanding how it maps to the object-oriented interface.
Stateful vs Object-Oriented
Pyplot maintains global state: calls like plt.plot() act on the current axes. The object-oriented (OO) API manipulates figure and axes objects explicitly. For quick experiments, Pyplot is convenient; for production code, prefer the OO style.
Quick Plot Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 50)
y = np.exp(x)
plt.plot(x, y, label="exp(x)")
plt.title("Exponential Growth")
plt.xlabel("x")
plt.ylabel("exp(x)")
plt.legend()
plt.show()Mapping to OO API
The following example replicates the Pyplot chart with explicit figure and axes references.
fig, ax = plt.subplots()
ax.plot(x, y, label="exp(x)")
ax.set_title("Exponential Growth")
ax.set_xlabel("x")
ax.set_ylabel("exp(x)")
ax.legend()
fig.show()This pattern scales better for complex dashboards and interactive applications.
Pyplot Utilities
plt.figure()— create a new figure and switch context.plt.subplot()— add a subplot (axes) to the current figure.plt.clf()/plt.cla()— clear figure or axes.plt.tight_layout()— adjust spacing to prevent label overlap.
Working in Notebooks
In IPython or Jupyter, enable interactive mode with %matplotlib inline or %matplotlib widget to control interactivity. Remember to document notebook plotting conventions when collaborating via info.studygrid@gmail.com.
Next Steps
Proceed to the plotting chapter to explore line charts, styling options, and data preparation techniques.
A Typical pyplot Workflow
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.title("Growth")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.savefig("growth.png") # export
plt.show() # displayEach plt. call modifies the "current" figure. When juggling several plots, switch to fig, ax = plt.subplots() to avoid confusion.
Try It Yourself
Exercise: Plot y = x for x in 0..5, label both axes, and add a title.
Show solution
import matplotlib.pyplot as plt
x = list(range(6))
plt.plot(x, x)
plt.title("Identity")
plt.xlabel("x"); plt.ylabel("y")
plt.show()Key Takeaways
pyplotkeeps a "current figure" you modify with each call.- Add title, labels, grid, then
showorsavefig.
📘 Real-World Deep Dive
Knowing <strong>Matplotlib Pyplot (Matplotlib)</strong> well is what turns Matplotlib from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Matplotlib Pyplot that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.xlabel("x"); plt.ylabel("y"); plt.title("Quadratic")
plt.show()Expected Output
(no output)Common mistakes
- Calling
plt.plotwithoutplt.show()in scripts (orplt.savefig) produces no visible output. - Passing mismatched array shapes to
plt.plot(x, y)raises a uselessValueError— verify shapes withx.shapeandy.shapefirst. - Mixing
numpy.float64withpandas.Seriesis OK, but mixingnumpy.datetime64with Pythondatetime.dateneeds an explicit cast. - Treating Matplotlib Pyplot as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- For large scatter plots use
plt.scatter(..., s=1, rasterised=True)or switch todatashader. - Use the
aggbackend on web services:import matplotlib; matplotlib.use("Agg"). - Plot once and reuse the figure: avoid embedding Matplotlib into tight Python loops without an explicit
clear(). - When working with Matplotlib, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.