By the end of this lesson, you will be able to create basic line plots using Matplotlib's Pyplot interface and display them in a window or notebook.
What it is
Pyplot is a module within the matplotlib library that provides a MATLAB-like interface for creating static, animated, and interactive visualizations. It manages a global state machine that tracks the current figure and axes, allowing you to build plots incrementally with simple function calls like plt.plot(), plt.title(), and plt.show().
The mental model is "stateful drawing": each command modifies the current active plot until you explicitly clear it or close the window. Related terms include Figure (the top-level container) and Axes (the plotting area).
Why it matters
- Rapid Prototyping: You can visualize data trends in just two lines of code without configuring complex object hierarchies.
- Simplicity: Ideal for quick checks during data analysis where customization is minimal.
- Standardization: Most tutorials and introductory resources use Pyplot, making it essential for learning broader Python data science workflows.
- Integration: Works seamlessly with NumPy arrays and Pandas DataFrames for immediate feedback on numerical data.
Syntax or steps
The smallest useful pattern involves importing the module, passing data to a plotting function, and displaying the result.
- Import
matplotlib.pyplotasplt. - Call
plt.plot(x_data, y_data)to draw lines. - Optionally add labels or titles using
plt.xlabel()orplt.title(). - Call
plt.show()to render the window.
Example
import matplotlib.pyplot as plt
# Sample data: x values [1, 2, 3] and corresponding y values [4, 5, 6]
x = [1, 2, 3]
y = [4, 5, 6]
# Create the plot
plt.plot(x, y, marker='o', linestyle='-')
# Add context
plt.title("Simple Linear Relationship")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
# Display the plot
plt.show()
Explanation: The plt.plot() function takes lists for X and Y coordinates. The marker='o' argument adds circles at each data point, while linestyle='-' ensures they are connected by solid lines. plt.show() blocks execution until the user closes the plot window, which is crucial when running scripts outside of Jupyter notebooks.
Common mistakes
- Forgetting
plt.show(): In standard Python scripts, omitting this results in no visible output because the buffer is never flushed to the screen. - Mismatched Array Lengths: Passing X and Y lists of different lengths raises a
ValueError. Always ensure dimensions match. - Overwriting Figures: Calling
plt.plot()multiple times withoutplt.figure()orplt.clf()draws on the same axes, potentially cluttering the view unintentionally. - Ignoring Backend Issues: In headless environments (like some servers),
plt.show()may fail unless you set the backend to 'Agg' viamatplotlib.use('Agg')before importing pyplot.
When to use it
Compare Pyplot with the Object-Oriented (OO) API (fig, ax = plt.subplots()). Use Pyplot for quick exploration; use the OO API for publication-quality figures requiring precise control over subplots and layout.
| Feature | Pyplot Interface | Object-Oriented API |
|---|---|---|
| Complexity | Low (Stateful) | High (Explicit objects) |
| Best For | Quick debugging, single plots | Multi-panel figures, reusable functions |
| Control | Limited to current active axes | Full access to Figure and Axes instances |
Practice
Guided Exercise: Plot the squares of numbers from 1 to 5. Use x = range(1, 6) and calculate y using a list comprehension. Add a title "Squares".
Challenge: Modify the guided exercise to plot both $x$ and $x^2$ on the same graph using two separate plt.plot() calls. How do you distinguish them visually?
Hint: Use the label parameter in plt.plot() and call plt.legend() before showing.
Quick check
Question: Why might a script run successfully but show no plot window?
Answer: The script likely omitted the plt.show() command, which is required to flush the drawing commands to the display backend in non-interactive environments.
Summary
Pyplot offers a concise, stateful approach to generating charts quickly, making it ideal for exploratory data analysis. While powerful for simple tasks, remember that complex layouts often require transitioning to the explicit Object-Oriented API for better maintainability and precision.