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

FunctionPurpose
plt.plot(x, y)Draw a line or marker plot
plt.scatter(x, y)Draw individual points
plt.bar(x, y)Draw vertical bars
plt.hist(data)Draw a histogram of a dataset
plt.xlabel() / plt.ylabel()Label the x-axis and y-axis
plt.title()Add a title above the plot
plt.legend()Show a legend describing each line
plt.grid()Add grid lines
plt.show()Display the figure
plt.savefig(path)Save the figure to a file

A typical pyplot workflow

  1. Prepare your data as lists or NumPy arrays
  2. Call a plotting function such as plt.plot() or plt.bar()
  3. Add context with plt.title(), plt.xlabel(), and plt.ylabel()
  4. Call plt.show() to display the figure, or plt.savefig() to write it to disk
Note: Call plt.savefig() before plt.show(). On some setups, plt.show() clears the current figure once the window closes, leaving nothing left to save afterward.

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?