0
0
Matplotlibdata~5 mins

Axes vs pyplot interface comparison in Matplotlib

Choose your learning style9 modes available
Introduction

We use plotting to see data clearly. Matplotlib offers two ways to make plots: the pyplot interface and the Axes interface. Knowing the difference helps you choose the best way to draw your charts.

When you want quick and simple plots for data exploration.
When you need to create multiple plots in one figure with precise control.
When you want to customize parts of a plot deeply, like axes labels or ticks.
When you are building complex figures with many subplots.
When you want to write reusable plotting functions that accept axes as input.
Syntax
Matplotlib
# Pyplot interface example
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.title('Title')
plt.show()

# Axes interface example
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Title')
plt.show()

The pyplot interface works like a simple drawing board where commands affect the current figure and axes.

The Axes interface gives you an object (ax) to control specific parts of the plot directly.

Examples
This uses the pyplot interface to quickly plot and add a title.
Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)
plt.title('Pyplot Interface')
plt.show()
This uses the Axes interface to plot and set the title on the axes object.
Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [4, 5, 6]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Axes Interface')
plt.show()
Using the Axes interface to create two side-by-side plots with different data and titles.
Matplotlib
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2)
axs[0].plot([1, 2, 3], [4, 5, 6])
axs[0].set_title('Left Plot')
axs[1].plot([1, 2, 3], [6, 5, 4])
axs[1].set_title('Right Plot')
plt.show()
Sample Program

This program shows the same plot twice: once using the pyplot interface and once using the Axes interface. Both produce the same visual result but use different ways to control the plot.

Matplotlib
import matplotlib.pyplot as plt

# Data
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

# Using pyplot interface
plt.plot(x, y, label='pyplot')
plt.title('Pyplot Interface Plot')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.legend()
plt.show()

# Using Axes interface
fig, ax = plt.subplots()
ax.plot(x, y, label='axes')
ax.set_title('Axes Interface Plot')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.legend()
plt.show()
OutputSuccess
Important Notes

The pyplot interface is easier for quick plots but less flexible for complex layouts.

The Axes interface is better for detailed control and multiple plots in one figure.

You can mix both, but it is best to stick to one style for clarity.

Summary

Pyplot interface is simple and good for quick plotting.

Axes interface gives more control and is better for complex figures.

Choose the interface based on your plotting needs and complexity.