Skip to content

Matplotlib - Pyplot API

matplotlib.pyplot is a collection of functions that provide a state-based interface to the Matplotlib library. This means that pyplot functions implicitly operate on the ‘current’ Figure and Axes. It’s designed to feel familiar to users of MATLAB.

Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area (Axes) in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

While convenient for simple, interactive plotting (like in a Jupyter Notebook), for more complex plots or within reusable scripts and applications, the Object-Oriented (OO) API is generally recommended. The OO API involves explicitly creating and managing Figure and Axes objects.

Here’s a categorized list of some commonly used pyplot functions:

FunctionDescription
plot()Plot y versus x as lines and/or markers.
scatter()Create a scatter plot of y vs x with varying marker size and/or color.
bar()Make a vertical bar plot.
barh()Make a horizontal bar plot.
hist()Plot a histogram.
boxplot()Make a box-and-whisker plot.
violinplot()Make a violin plot (combines boxplot and density).
pie()Plot a pie chart. (Use with caution, bar charts are often better).
imshow()Display data as an image; i.e., on a 2D regular raster.
contour() / contourf()Plot contour lines / filled contours.
quiver()Plot a 2D field of arrows (vector field).
step()Make a step plot.
fill_between()Fill the area between two horizontal curves.
FunctionDescription
figure()Create a new figure or activate an existing figure.
subplot() / subplots()Add a subplot to the current figure / Create a figure and a set of subplots.
axes()Add an Axes to the current figure.
gca()Get the current Axes instance.
gcf()Get the current Figure instance.
show()Display all open figures.
savefig()Save the current figure to a file.
close()Close a figure window.
clf()Clear the current figure.
cla()Clear the current Axes.
FunctionDescription
title()Set a title for the current Axes.
xlabel() / ylabel()Set the label for the x-axis / y-axis.
xlim() / ylim()Get or set the x / y limits of the current Axes.
xticks() / yticks()Get or set the current tick locations and labels of the x / y axis.
legend()Place a legend on the current Axes.
grid()Configure the grid lines.
text()Add text to the current Axes.
annotate()Annotate the plot with text and optionally an arrow.

Remember, using pyplot modifies the global state. Calling plt.plot() followed by plt.title() implicitly applies the title to the Axes that plt.plot() operated on.

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
plt.figure(figsize=(6, 4)) # Create a new figure
plt.plot(x, y, label='sin(x)') # Plot data on the current Axes
plt.title('Simple Sine Wave') # Add title to current Axes
plt.xlabel('Radians') # Add x-label
plt.ylabel('Value') # Add y-label
plt.legend() # Add legend
plt.grid(True) # Add grid
plt.show() # Display the figure