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.
Axes vs pyplot interface comparison in 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.
import matplotlib.pyplot as plt x = [1, 2, 3] y = [4, 5, 6] plt.plot(x, y) plt.title('Pyplot Interface') plt.show()
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()
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()
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.
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()
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.
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.