Matplotlib Figure and Axes Management Functions
Matplotlib Reference Documentation
Matplotlib provides a series of functions for creating and managing Figure and Axes objects. All related functions are listed below.
Function List
| Function | Description | pyplot | Corresponding Method |
|---|---|---|---|
| figure() | Create or activate a Figure | plt.figure() | - |
| subplots() | Create a Figure and Axes grid | plt.subplots() | fig.subplots() |
| subplot() | Add a single subplot by row and column index | plt.subplot() | fig.add_subplot() |
| subplot2grid() | Create a subplot at a specified position in the grid | plt.subplot2grid() | - |
| subplot_mosaic() | Layout subplots with label strings | plt.subplot_mosaic() | fig.subplot_mosaic() |
| axes() | Add an Axes to the current Figure | plt.axes() | fig.add_axes() |
| gca() | Get the current Axes | plt.gca() | fig.gca() |
| gcf() | Get the current Figure | plt.gcf() | - |
| sca() | Set the current Axes | plt.sca(ax) | fig.sca(ax) |
| cla() | Clear the current Axes | plt.cla() | ax.cla() |
| clf() | Clear the current Figure | plt.clf() | fig.clear() |
| close() | Close the Figure window | plt.close() | - |
| delaxes() | Remove Axes from a Figure | plt.delaxes(ax) | fig.delaxes(ax) |
| fignum_exists() | Check whether a Figure number exists | plt.fignum_exists(n) | - |
| get_figlabels() | Get a list of all Figure labels | plt.get_figlabels() | - |
| get_fignums() | Get a list of all Figure numbers | plt.get_fignums() | - |
| twinx() | Create a twin y-axis sharing the x-axis | plt.twinx() | ax.twinx() |
| twiny() | Create a twin x-axis sharing the y-axis | plt.twiny() | ax.twiny() |
Usage Examples
Example 1: gca/gcf/sca operating on the current figure
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# Create the first Figure
plt.figure(1)
plt.plot(x, np.sin(x), label='sin(x)')
# Create the second Figure
plt.figure(2)
plt.plot(x, np.cos(x), label='cos(x)')
# Check whether Figure 1 exists
print(plt.fignum_exists(1)) # True
# Get all Figure numbers
print(plt.get_fignums()) # [1, 2]
# Switch back to Figure 1
plt.figure(1)
ax = plt.gca() # Get the current Axes
print(ax.get_title())
# Set the current Axes to another one
plt.sca(ax)
plt.title('Switched via sca()')
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
# Create the first Figure
plt.figure(1)
plt.plot(x, np.sin(x), label='sin(x)')
# Create the second Figure
plt.figure(2)
plt.plot(x, np.cos(x), label='cos(x)')
# Check whether Figure 1 exists
print(plt.fignum_exists(1)) # True
# Get all Figure numbers
print(plt.get_fignums()) # [1, 2]
# Switch back to Figure 1
plt.figure(1)
ax = plt.gca() # Get the current Axes
print(ax.get_title())
# Set the current Axes to another one
plt.sca(ax)
plt.title('Switched via sca()')
plt.show()
True [1, 2]
Example 2: Creating a non-uniform layout with subplot2grid
Example
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10, 6), layout='constrained')
# subplot2grid(shape, loc, rowspan, colspan)
# shape=(3,3): a grid of 3 rows and 3 columns
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # Top spans the entire row
ax2 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # Left spans 2 rows vertically
ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2) # Top right spans 2 columns
ax4 = plt.subplot2grid((3, 3), (2, 1)) # Right middle
ax5 = plt.subplot2grid((3, 3), (2, 2)) # Right bottom
x = np.linspace(0, 10, 50)
ax1.plot(x, np.sin(x))
ax1.set_title('Top: colspan=3')
ax2.plot(x, np.cos(x), 'orange')
ax2.set_title('Left: rowspan=2')
ax3.bar(['A','B','C'], [3,7,5])
ax3.set_title('Right Top: colspan=2')
ax4.text(0.5, 0.5, 'Panel 4', ha='center', va='center')
ax5.text(0.5, 0.5, 'Panel 5', ha='center', va='center')
fig.suptitle('subplot2grid Layout', fontsize=14)
plt.show()
import numpy as np
fig = plt.figure(figsize=(10, 6), layout='constrained')
# subplot2grid(shape, loc, rowspan, colspan)
# shape=(3,3): a grid of 3 rows and 3 columns
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # Top spans the entire row
ax2 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # Left spans 2 rows vertically
ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2) # Top right spans 2 columns
ax4 = plt.subplot2grid((3, 3), (2, 1)) # Right middle
ax5 = plt.subplot2grid((3, 3), (2, 2)) # Right bottom
x = np.linspace(0, 10, 50)
ax1.plot(x, np.sin(x))
ax1.set_title('Top: colspan=3')
ax2.plot(x, np.cos(x), 'orange')
ax2.set_title('Left: rowspan=2')
ax3.bar(['A','B','C'], [3,7,5])
ax3.set_title('Right Top: colspan=2')
ax4.text(0.5, 0.5, 'Panel 4', ha='center', va='center')
ax5.text(0.5, 0.5, 'Panel 5', ha='center', va='center')
fig.suptitle('subplot2grid Layout', fontsize=14)
plt.show()
Example 3: subplot_mosaic label layout
Example
import matplotlib.pyplot as plt
import numpy as np
layout = """
AAAB
CCDD
"""
fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6),
layout='constrained')
x = np.linspace(0, 10, 100)
# Access subplots by label name
axes['A'].plot(x, np.sin(x))
axes['A'].set_title('A: Top wide panel')
axes['B'].plot(x, np.cos(x), 'orange')
axes['B'].set_title('B: Top right')
axes['C'].bar(['X','Y','Z'], [5, 8, 3], color='steelblue')
axes['C'].set_title('C: Bottom left')
axes['D'].hist(np.random.randn(200), bins=20,
color='coral', edgecolor='white')
axes['D'].set_title('D: Bottom right')
fig.suptitle('subplot_mosaic() with Label Access')
plt.show()
import numpy as np
layout = """
AAAB
CCDD
"""
fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6),
layout='constrained')
x = np.linspace(0, 10, 100)
# Access subplots by label name
axes['A'].plot(x, np.sin(x))
axes['A'].set_title('A: Top wide panel')
axes['B'].plot(x, np.cos(x), 'orange')
axes['B'].set_title('B: Top right')
axes['C'].bar(['X','Y','Z'], [5, 8, 3], color='steelblue')
axes['C'].set_title('C: Bottom left')
axes['D'].hist(np.random.randn(200), bins=20,
color='coral', edgecolor='white')
axes['D'].set_title('D: Bottom right')
fig.suptitle('subplot_mosaic() with Label Access')
plt.show()
Example 4: twinx/twiny dual axes
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots(figsize=(8, 4), layout='constrained')
# Primary y-axis (left side)
color1 = 'tab:blue'
ax1.plot(x, np.sin(x) * 100, color=color1, label='Voltage')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Voltage (mV)', color=color1)
ax1.tick_params(axis='y', labelcolor=color1)
# twinx() creates a twin y-axis sharing the x-axis (right side)
ax2 = ax1.twinx()
color2 = 'tab:red'
ax2.plot(x, np.cos(x) * 40 + 50, color=color2, linestyle='--',
label='Temperature')
ax2.set_ylabel('Temperature (°C)', color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
ax1.set_title('Dual Y-Axes with twinx()')
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots(figsize=(8, 4), layout='constrained')
# Primary y-axis (left side)
color1 = 'tab:blue'
ax1.plot(x, np.sin(x) * 100, color=color1, label='Voltage')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Voltage (mV)', color=color1)
ax1.tick_params(axis='y', labelcolor=color1)
# twinx() creates a twin y-axis sharing the x-axis (right side)
ax2 = ax1.twinx()
color2 = 'tab:red'
ax2.plot(x, np.cos(x) * 40 + 50, color=color2, linestyle='--',
label='Temperature')
ax2.set_ylabel('Temperature (°C)', color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
ax1.set_title('Dual Y-Axes with twinx()')
plt.show()
Example 5: cla/clf/close cleanup operations
Example
import matplotlib.pyplot as plt
import numpy as np
# Create a Figure and plot
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Original Plot')
print('Before cla():', len(ax.get_lines())) # 1
# cla() clears the Axes contents (retains the Axes and Figure)
ax.cla()
print('After cla():', len(ax.get_lines())) # 0
# Replot
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title('After cla() and replot')
plt.show()
# clf() clears the entire Figure
plt.clf()
print('After clf():', len(fig.get_axes())) # 0
# close() closes the Figure window
plt.close('all')
print('example: cleanup complete')
import numpy as np
# Create a Figure and plot
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Original Plot')
print('Before cla():', len(ax.get_lines())) # 1
# cla() clears the Axes contents (retains the Axes and Figure)
ax.cla()
print('After cla():', len(ax.get_lines())) # 0
# Replot
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title('After cla() and replot')
plt.show()
# clf() clears the entire Figure
plt.clf()
print('After clf():', len(fig.get_axes())) # 0
# close() closes the Figure window
plt.close('all')
print('example: cleanup complete')
Other Extensions