Matplotlib - Figure Class
Matplotlib - The Figure Class
Section titled “Matplotlib - The 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 Axesfig, ax = plt.subplots()
# Create a Figure with a 2x2 grid of Axesfig, 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 subplotax2 = 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:
| Parameter | Description |
|---|---|
figsize | A tuple (width, height) in inches. Controls the physical size of the Figure. |
dpi | Dots Per Inch. Controls the resolution of the Figure. |
facecolor | The background color of the Figure. |
edgecolor | The border color of the Figure. |
linewidth | The width of the border line. |
layout | Specifies the layout engine (e.g., ‘constrained’, ‘tight’) to automatically adjust subplot parameters for a tight layout. Recommended over plt.tight_layout(). |
Example:
Section titled “Example:”# Create a Figure with specific size and resolutionfig = 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 figureThe 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.