Matplotlib Layout and Configuration Functions
Matplotlib Reference Documentation
Layout functions control subplot spacing and arrangement, configuration functions manage Matplotlib global parameters.
Function Overview
Layout Functions
| Function | Description |
|---|---|
| subplots_adjust() | Manually adjust subplot spacing |
| tight_layout() | Automatic compact layout |
| margins() | Set data margins (whitespace at both ends of the axes) |
| subplot_tool() | Launch interactive subplot adjustment tool |
Configuration Functions
| Function | Description |
|---|---|
| rc() | Set rc parameters (supports batch setting) |
| rc_context() | Context manager for temporarily setting rc parameters |
| rcdefaults() | Restore all rc parameters to default values |
Colormap Functions
| Function | Description |
|---|---|
| clim() | Set the data range for color mapping |
| get_cmap() | Get the colormap with the specified name |
| set_cmap() | Set the default colormap |
| gci() | Get the current color-mappable object |
| sci() | Set the current color-mappable object |
| imread() | Read an image from a file into an array |
| imsave() | Save an array as an image file |
Output and Interaction Functions
| Function | Description |
|---|---|
| show() | Display all opened Figures |
| draw() | Force re-render the current Figure |
| draw_if_interactive() | Render Figure in interactive mode |
| pause() | Pause for the specified number of seconds (processes GUI events during the pause) |
| ion() / ioff() | Enable/disable interactive mode |
| isinteractive() | Check whether currently in interactive mode |
| install_repl_displayhook() | Install REPL display hook |
| uninstall_repl_displayhook() | Uninstall REPL display hook |
| switch_backend() | Switch Matplotlib backend |
Layout Function Examples
subplots_adjust() / tight_layout() / margins()
matplotlib.pyplot.subplots_adjust(left=None, bottom=None, right=None,
top=None, wspace=None, hspace=None)
matplotlib.pyplot.tight_layout(*, pad=1.08, h_pad=None, w_pad=None,
rect=None)
matplotlib.pyplot.margins(*margins, x=None, y=None, tight=True)
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# Manual control with subplots_adjust
fig.subplots_adjust(left=0.1, right=0.95,
top=0.9, bottom=0.1,
hspace=0.4, wspace=0.3)
for i, ax in enumerate(axes.flatten()):
ax.plot(x, np.sin(x + i))
ax.set_title(f'Plot {i+1}')
ax.set_xlabel('A long x label')
ax.set_ylabel('A long y label')
# Set margins
ax.margins(x=0.1, y=0.15)
fig.suptitle('subplots_adjust() + margins()', fontsize=14)
plt.show()
print("example: layout example")
import numpy as np
x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# Manual control with subplots_adjust
fig.subplots_adjust(left=0.1, right=0.95,
top=0.9, bottom=0.1,
hspace=0.4, wspace=0.3)
for i, ax in enumerate(axes.flatten()):
ax.plot(x, np.sin(x + i))
ax.set_title(f'Plot {i+1}')
ax.set_xlabel('A long x label')
ax.set_ylabel('A long y label')
# Set margins
ax.margins(x=0.1, y=0.15)
fig.suptitle('subplots_adjust() + margins()', fontsize=14)
plt.show()
print("example: layout example")
Configuration Function Examples
rc() / rc_context() / rcdefaults()
matplotlib.pyplot.rc(group, **kwargs) matplotlib.pyplot.rc_context(rc=None, fname=None) matplotlib.pyplot.rcdefaults()
Example
import matplotlib.pyplot as plt
import numpy as np
# Method 1: Set rcParams globally
plt.rcParams['font.size'] = 12
plt.rcParams['axes.grid'] = True
# Method 2: Use rc() to set in batch
plt.rc('lines', linewidth=2, color='steelblue')
plt.rc('axes', titlesize=14, grid=True)
x = np.linspace(0, 10, 50)
# rc_context temporary setting (only valid within the with block)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# ax1 uses global rc settings
ax1.plot(x, np.sin(x))
ax1.set_title('Global rc settings')
# ax2 uses temporary style override
with plt.rc_context({'lines.color': 'coral',
'lines.linestyle': '--',
'axes.facecolor': '#f0f0f0'}):
ax2.plot(x, np.cos(x))
ax2.set_title('rc_context() overrides')
plt.show()
# Restore defaults
plt.rcdefaults()
print("example: rc settings restored to defaults")
import numpy as np
# Method 1: Set rcParams globally
plt.rcParams['font.size'] = 12
plt.rcParams['axes.grid'] = True
# Method 2: Use rc() to set in batch
plt.rc('lines', linewidth=2, color='steelblue')
plt.rc('axes', titlesize=14, grid=True)
x = np.linspace(0, 10, 50)
# rc_context temporary setting (only valid within the with block)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# ax1 uses global rc settings
ax1.plot(x, np.sin(x))
ax1.set_title('Global rc settings')
# ax2 uses temporary style override
with plt.rc_context({'lines.color': 'coral',
'lines.linestyle': '--',
'axes.facecolor': '#f0f0f0'}):
ax2.plot(x, np.cos(x))
ax2.set_title('rc_context() overrides')
plt.show()
# Restore defaults
plt.rcdefaults()
print("example: rc settings restored to defaults")
Colormap Function Examples
clim() / get_cmap() / set_cmap()
matplotlib.pyplot.clim(vmin=None, vmax=None) matplotlib.pyplot.get_cmap(name=None, lut=None) matplotlib.pyplot.set_cmap(cmap)
Example
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
# View the current default colormap
print('Default cmap:', plt.rcParams['image.cmap'])
# Get a specific colormap
cmap = plt.get_cmap('plasma')
print('Got cmap:', cmap.name)
fig, ax = plt.subplots(figsize=(5, 4), layout='constrained')
im = ax.imshow(data, cmap='hot', vmin=0.2, vmax=0.8)
# clim() can also be used to modify the range
plt.clim(0.1, 0.9)
fig.colorbar(im, ax=ax, label='Value')
ax.set_title('imshow with clim()')
plt.show()
# Set the global default colormap
plt.set_cmap('Blues')
print('New default cmap:', plt.rcParams['image.cmap'])
import numpy as np
data = np.random.rand(10, 10)
# View the current default colormap
print('Default cmap:', plt.rcParams['image.cmap'])
# Get a specific colormap
cmap = plt.get_cmap('plasma')
print('Got cmap:', cmap.name)
fig, ax = plt.subplots(figsize=(5, 4), layout='constrained')
im = ax.imshow(data, cmap='hot', vmin=0.2, vmax=0.8)
# clim() can also be used to modify the range
plt.clim(0.1, 0.9)
fig.colorbar(im, ax=ax, label='Value')
ax.set_title('imshow with clim()')
plt.show()
# Set the global default colormap
plt.set_cmap('Blues')
print('New default cmap:', plt.rcParams['image.cmap'])
Default cmap: viridis Got cmap: plasma New default cmap: Blues
imread() / imsave()
matplotlib.pyplot.imread(fname, format=None) matplotlib.pyplot.imsave(fname, arr, **kwargs)
Example
import matplotlib.pyplot as plt
import numpy as np
# Create image data
img = np.random.rand(50, 50)
# Save as PNG (no Figure required)
plt.imsave('example_temp_image.png', img,
cmap='viridis')
print("example: image saved via imsave()")
# Read it back
loaded = plt.imread('example_temp_image.png')
print("Loaded shape:", loaded.shape)
print("example: image loaded via imread()")
import numpy as np
# Create image data
img = np.random.rand(50, 50)
# Save as PNG (no Figure required)
plt.imsave('example_temp_image.png', img,
cmap='viridis')
print("example: image saved via imsave()")
# Read it back
loaded = plt.imread('example_temp_image.png')
print("Loaded shape:", loaded.shape)
print("example: image loaded via imread()")
Loaded shape: (50, 50, 4)
Output and Interaction Function Examples
ion() / ioff() / pause() / draw()
matplotlib.pyplot.ion() # 开启交互模式 matplotlib.pyplot.ioff() # 关闭交互模式 matplotlib.pyplot.isinteractive() # 检查状态 matplotlib.pyplot.pause(interval) # 暂停并处理事件 matplotlib.pyplot.draw() # 强制重绘
Example
import matplotlib.pyplot as plt
import numpy as np
# Interactive mode example (run in an environment that supports interaction)
print('Interactive mode:', plt.isinteractive())
# Manual control of rendering in non-interactive mode
plt.ioff()
fig, ax = plt.subplots()
x = np.linspace(0, 10, 100)
for i in range(3):
ax.clear()
ax.plot(x, np.sin(x + i * 0.5))
ax.set_title(f'Frame {i+1}')
plt.draw() # Manually render
plt.pause(0.5) # Pause for 0.5 seconds
plt.show()
print("example: animation complete")
import numpy as np
# Interactive mode example (run in an environment that supports interaction)
print('Interactive mode:', plt.isinteractive())
# Manual control of rendering in non-interactive mode
plt.ioff()
fig, ax = plt.subplots()
x = np.linspace(0, 10, 100)
for i in range(3):
ax.clear()
ax.plot(x, np.sin(x + i * 0.5))
ax.set_title(f'Frame {i+1}')
plt.draw() # Manually render
plt.pause(0.5) # Pause for 0.5 seconds
plt.show()
print("example: animation complete")
switch_backend()
matplotlib.pyplot.switch_backend(newbackend)
switch_backend() can only be called after the first import of pyplot and before creating any Figure. To switch backends after creating a Figure, you need to use the experimental
matplotlib.use()。
Other Extensions