Matplotlib figure() Function


Matplotlib 参考文档Matplotlib Reference Documentation

figure()Used to create a new Figure (canvas) or activate an existing Figure.

Figure is the top-level container for all plots, managing the size, DPI, and all subplots of the entire chart.

Function Definition

matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, *,
    facecolor=None, edgecolor=None, frameon=True,
    FigureClass=<class 'matplotlib.figure.Figure'>,
    clear=False, layout=None, **kwargs)

Parameter Description

ParameterTypeDescription
numint or strFigure identifier. Integers are numbers, strings are labels. If it does not exist, a new one is created; if it exists, the existing one is activated.
figsizetuple (w, h)Figure size (in inches), e.g., (8, 6). Default is determined by rcParams.
dpifloatResolution (dots per inch), e.g., 100. Affects the output pixel size.
facecolorcolorFigure background color
edgecolorcolorFigure edge color
frameonboolWhether to display the Figure background frame, default True
clearboolIf num already exists, whether to clear it first before using it
layoutstr or LayoutEngineRecommendedLayout engine: 'constrained', 'compressed', 'tight', 'none'

Rarely called directly in daily use,figure()more commonlysubplots()creates the Figure and Axes in one call. Using figure() alone is mainly for multi-Figure scenarios or custom canvas properties.


Usage Examples

Example 1: Creating a Figure with Custom Size

Example

import matplotlib.pyplot as plt
import numpy as np

# Create a Figure with specified size and high DPI
fig = plt.figure(figsize=(10, 4), dpi=100,
                 facecolor='#f8f9fa',
                 layout='constrained')

# Manually add subplots
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)

x = np.linspace(0, 10, 100)
ax1.plot(x, np.sin(x), 'steelblue', linewidth=2)
ax1.set_title('Plot 1')

ax2.plot(x, np.cos(x), 'coral', linewidth=2)
ax2.set_title('Plot 2')

plt.show()

Example 2: Managing Multiple Figures

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

# Create Figure #1
fig1 = plt.figure(1, figsize=(6, 4))
ax1 = fig1.subplots()
ax1.plot(x, np.sin(x), 'blue')
ax1.set_title('Figure 1: sin(x)')

# Create Figure #2
fig2 = plt.figure(2, figsize=(6, 4))
ax2 = fig2.subplots()
ax2.plot(x, np.cos(x), 'red')
ax2.set_title('Figure 2: cos(x)')

# Activate Figure #1 and continue working
plt.figure(1)
plt.plot(x, np.sin(2*x), '--', alpha=0.5)

# Save a specific Figure
fig1.savefig('example_fig1.png', dpi=150)
fig2.savefig('example_fig2.png', dpi=150)
print("example: two figures saved")

plt.show()

Example 3: Automatic Layout with the layout Parameter

Example

import matplotlib.pyplot as plt
import numpy as np

# Compare layout settings

# Without using layout (labels may overlap)
fig1 = plt.figure(1, figsize=(8, 4))
for i in range(3):
    ax = fig1.add_subplot(1, 3, i+1)
    ax.plot(np.random.randn(50).cumsum())
    ax.set_title(f'Plot {i+1}')
    ax.set_xlabel('A very long x label')

# Use layout='constrained' (automatically handles overlapping)
fig2 = plt.figure(2, figsize=(8, 4), layout='constrained')
for i in range(3):
    ax = fig2.add_subplot(1, 3, i+1)
    ax.plot(np.random.randn(50).cumsum())
    ax.set_title(f'Plot {i+1}')
    ax.set_xlabel('A very long x label')

plt.figure(1)
plt.suptitle('Without layout', y=1.02)
plt.figure(2)
plt.suptitle('With layout="constrained"', y=1.02)
plt.show()
print("example: compare layout settings")

FAQ

What is the unit of figsize?

Inches. Actual pixel size = figsize × dpi. For examplefigsize=(8,6), dpi=100generates an 800×600 pixel image.

Which layout option is best?

'constrained'is the recommended option for most scenarios, automatically handling subplot and label spacing.

'compressed'further compresses the margins, suitable for scenarios that need to maximize the data area.

'none'does not use automatic layout (default), and can be manually adjusted via subplots_adjust().


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions