Matplotlib Pyplot
The pyplot module is Matplotlib's easy, command-style interface for building charts step by step.
What is pyplot?
matplotlib.pyplot is a module inside Matplotlib that provides a collection of functions behaving much like MATLAB's plotting commands. Instead of manually creating figure and axes objects yourself, you call short functions such as plt.plot(), plt.title(), and plt.show(), and pyplot keeps track of the current figure and axes for you behind the scenes.
Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.show()Figures and Axes behind the scenes
Every pyplot command actually operates on two underlying objects: a Figure, which is the entire window or image, and an Axes, which is the individual plot area with its own x-axis and y-axis living inside that figure. When you call plt.plot() without creating anything first, pyplot automatically creates a Figure and an Axes for you, then draws onto them.
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(6, 4))
plt.plot(x, y)
plt.title("Sine Wave")
plt.show()Common pyplot functions
A typical pyplot workflow
- Prepare your data as lists or NumPy arrays
- Call a plotting function such as plt.plot() or plt.bar()
- Add context with plt.title(), plt.xlabel(), and plt.ylabel()
- Call plt.show() to display the figure, or plt.savefig() to write it to disk
Because pyplot always tracks a 'current' figure and axes, you can build a chart across several lines of code, adding one piece at a time, before finally displaying or saving it.
Exercise: Matplotlib Pyplot
What kind of interface does the matplotlib.pyplot module provide?