What's the difference between Matplotlib.pyplot and Matplotlib.figure?

The key difference lies in their roles: matplotlib.pyplot provides a MATLAB-like interface for creating plots, while matplotlib.figure represents the actual figure container that holds all plot elements.

matplotlib.pyplot

The matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: creates a figure, creates a plotting area, plots lines, adds labels, etc.

In matplotlib.pyplot, various states are preserved across function calls, so it keeps track of things like the current figure and plotting area, directing plotting functions to the current axes.

Example

import matplotlib.pyplot as plt
import numpy as np

# Using pyplot interface (stateful)
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(8, 4))
plt.plot(x, y, label='sin(x)')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Using pyplot interface')
plt.legend()
plt.grid(True)
plt.show()

matplotlib.figure

The matplotlib.figure keeps track of all child Axes, special artists (titles, figure legends, etc.), and the canvas. A figure can contain any number of Axes, but typically has at least one.

The Figure class provides more explicit control over the plotting process and is preferred for object-oriented programming approaches.

Example

import matplotlib.pyplot as plt
import matplotlib.figure as figure
import numpy as np

# Using Figure class (object-oriented)
x = np.linspace(0, 10, 100)
y = np.cos(x)

fig = figure.Figure(figsize=(8, 4))
ax = fig.add_subplot(111)
ax.plot(x, y, label='cos(x)', color='red')
ax.set_xlabel('X values')
ax.set_ylabel('Y values')
ax.set_title('Using Figure class')
ax.legend()
ax.grid(True)

# Need to display with pyplot
plt.show()

Key Differences

Aspect matplotlib.pyplot matplotlib.figure
Interface Style MATLAB-like (stateful) Object-oriented
State Management Automatic Explicit
Best For Quick plots, scripts Complex applications, GUIs
Control Level High-level convenience Low-level precision

Creating Figure Windows

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create a named figure window
fig = plt.figure("Custom Figure Window")
plt.text(0.5, 0.5, 'Hello Figure!', ha='center', va='center', fontsize=16)
plt.axis('off')
plt.show()

Conclusion

Use pyplot for quick plotting and scripting with its convenient MATLAB-like interface. Use Figure class for object-oriented applications requiring explicit control over plot elements and complex layouts.

Updated on: 2026-03-25T23:01:39+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements