Skip to content

Matplotlib - Figure Class

The matplotlib.figure.Figure class represents the top-level container for all plot elements in Matplotlib. Think of it as the canvas upon which everything else (like plots, titles, legends) is drawn.

You typically don’t instantiate Figure directly. Instead, the recommended way to create a Figure and associated Axes (the actual plotting area) is by using the pyplot.subplots() function:

import matplotlib.pyplot as plt
# Create a Figure and a single Axes
fig, ax = plt.subplots()
# Create a Figure with a 2x2 grid of Axes
fig, axes = plt.subplots(nrows=2, ncols=2)

Alternatively, you can create a figure using pyplot.figure(), and then add Axes manually, which offers more control over placement:

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1) # Add a standard subplot
ax2 = fig.add_axes([0.2, 0.2, 0.4, 0.4]) # Add an Axes at a specific location [left, bottom, width, height]

When creating a Figure using plt.figure() or plt.subplots(), you can specify several parameters to control its appearance:

ParameterDescription
figsizeA tuple (width, height) in inches. Controls the physical size of the Figure.
dpiDots Per Inch. Controls the resolution of the Figure.
facecolorThe background color of the Figure.
edgecolorThe border color of the Figure.
linewidthThe width of the border line.
layoutSpecifies the layout engine (e.g., ‘constrained’, ‘tight’) to automatically adjust subplot parameters for a tight layout. Recommended over plt.tight_layout().
# Create a Figure with specific size and resolution
fig = plt.figure(figsize=(8, 6), dpi=100, facecolor='lightgray', layout='constrained')
ax = fig.add_subplot(111)
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Figure with Custom Parameters')
plt.show() # Display the figure

The Figure object acts as the main container, holding references to all its Axes, artists (like lines, text), legends, etc. You’ll often interact with the Axes objects contained within the Figure to perform most plotting operations.