Funciones de diseño y configuración de Matplotlib
Documentación de referencia de Matplotlib
Las funciones de diseño controlan el espaciado y la disposición de los subplots, y las funciones de configuración gestionan los parámetros globales de Matplotlib.
Resumen de funciones
Funciones de diseño
| Función | Descripción |
|---|---|
| subplots_adjust() | Ajustar manualmente el espaciado entre subplots |
| tight_layout() | Diseño automático compacto |
| margins() | Establecer el margen de datos (espacio en blanco en los extremos de los ejes) |
| subplot_tool() | Iniciar la herramienta de ajuste interactivo de subplots |
Funciones de configuración
| Función | Descripción |
|---|---|
| rc() | Establecer los parámetros rc (admite configuración por lotes) |
| rc_context() | Administrador de contexto para establecer temporalmente los parámetros rc |
| rcdefaults() | Restablecer todos los parámetros rc a sus valores predeterminados |
Funciones de colormap
| Función | Descripción |
|---|---|
| clim() | Establecer el rango de datos del colormap |
| get_cmap() | Obtener el colormap con el nombre especificado |
| set_cmap() | Establecer el colormap predeterminado |
| gci() | Obtener el objeto actual de mapeo de color |
| sci() | Establecer el objeto actual de mapeo de color |
| imread() | Leer una imagen de un archivo a un array |
| imsave() | Guardar un array como archivo de imagen |
Funciones de salida e interacción
| Función | Descripción |
|---|---|
| show() | Mostrar todas las Figures abiertas |
| draw() | Forzar el re-renderizado de la Figure actual |
| draw_if_interactive() | Renderizar la Figure en modo interactivo |
| pause() | Pausar durante los segundos especificados (procesa eventos de GUI durante la pausa) |
| ion() / ioff() | Activar/desactivar el modo interactivo |
| isinteractive() | Comprobar si está en modo interactivo |
| install_repl_displayhook() | Instalar el hook de visualización de REPL |
| uninstall_repl_displayhook() | Desinstalar el hook de visualización de REPL |
| switch_backend() | Cambiar el backend de Matplotlib |
Ejemplo de funciones de diseño
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)
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# subplots_adjust control manual
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')
# Configurar márgenes
ax.margins(x=0.1, y=0.15)
fig.suptitle('subplots_adjust() + margins()', fontsize=14)
plt.show()
print("ejemplo: layout example")
import numpy as np
x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# subplots_adjust control manual
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')
# Configurar márgenes
ax.margins(x=0.1, y=0.15)
fig.suptitle('subplots_adjust() + margins()', fontsize=14)
plt.show()
print("ejemplo: layout example")
Ejemplo de funciones de configuración
rc() / rc_context() / rcdefaults()
matplotlib.pyplot.rc(group, **kwargs) matplotlib.pyplot.rc_context(rc=None, fname=None) matplotlib.pyplot.rcdefaults()
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
# Método 1: configurar rcParams globalmente
plt.rcParams['font.size'] = 12
plt.rcParams['axes.grid'] = True
# Método 2: configurar en lote con rc()
plt.rc('lines', linewidth=2, color='steelblue')
plt.rc('axes', titlesize=14, grid=True)
x = np.linspace(0, 10, 50)
# Configuración temporal con rc_context (solo válida dentro del bloque with)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# ax1 usa la configuración rc global
ax1.plot(x, np.sin(x))
ax1.set_title('Global rc settings')
# ax2 usa una sobrescritura de estilo temporal
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()
# Restaurar valores predeterminados
plt.rcdefaults()
print("ejemplo: rc settings restored to defaults")
import numpy as np
# Método 1: configurar rcParams globalmente
plt.rcParams['font.size'] = 12
plt.rcParams['axes.grid'] = True
# Método 2: configurar en lote con rc()
plt.rc('lines', linewidth=2, color='steelblue')
plt.rc('axes', titlesize=14, grid=True)
x = np.linspace(0, 10, 50)
# Configuración temporal con rc_context (solo válida dentro del bloque with)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# ax1 usa la configuración rc global
ax1.plot(x, np.sin(x))
ax1.set_title('Global rc settings')
# ax2 usa una sobrescritura de estilo temporal
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()
# Restaurar valores predeterminados
plt.rcdefaults()
print("ejemplo: rc settings restored to defaults")
Ejemplo de funciones de colormap
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)
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
# Ver el colormap predeterminado actual
print('Default cmap:', plt.rcParams['image.cmap'])
# Obtener un colormap específico
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() también se puede usar para modificar el rango
plt.clim(0.1, 0.9)
fig.colorbar(im, ax=ax, label='Value')
ax.set_title('imshow with clim()')
plt.show()
# Configurar el colormap predeterminado global
plt.set_cmap('Blues')
print('New default cmap:', plt.rcParams['image.cmap'])
import numpy as np
data = np.random.rand(10, 10)
# Ver el colormap predeterminado actual
print('Default cmap:', plt.rcParams['image.cmap'])
# Obtener un colormap específico
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() también se puede usar para modificar el rango
plt.clim(0.1, 0.9)
fig.colorbar(im, ax=ax, label='Value')
ax.set_title('imshow with clim()')
plt.show()
# Configurar el colormap predeterminado global
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)
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
# Crear datos de imagen
img = np.random.rand(50, 50)
# Guardar como PNG (sin necesidad de Figure)
plt.imsave('ejemplo_temp_image.png', img,
cmap='viridis')
print("ejemplo: image saved via imsave()")
# Volver a leerlo
loaded = plt.imread('ejemplo_temp_image.png')
print("Loaded shape:", loaded.shape)
print("ejemplo: image loaded via imread()")
import numpy as np
# Crear datos de imagen
img = np.random.rand(50, 50)
# Guardar como PNG (sin necesidad de Figure)
plt.imsave('ejemplo_temp_image.png', img,
cmap='viridis')
print("ejemplo: image saved via imsave()")
# Volver a leerlo
loaded = plt.imread('ejemplo_temp_image.png')
print("Loaded shape:", loaded.shape)
print("ejemplo: image loaded via imread()")
Loaded shape: (50, 50, 4)
Ejemplo de funciones de salida e interacción
ion() / ioff() / pause() / draw()
matplotlib.pyplot.ion() # 开启交互模式 matplotlib.pyplot.ioff() # 关闭交互模式 matplotlib.pyplot.isinteractive() # 检查状态 matplotlib.pyplot.pause(interval) # 暂停并处理事件 matplotlib.pyplot.draw() # 强制重绘
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
# Ejemplo de modo interactivo (ejecutar en un entorno interactivo)
print('Interactive mode:', plt.isinteractive())
# Control manual del renderizado en modo no interactivo
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() # Renderizado manual
plt.pause(0.5) # Pausar 0.5 segundos
plt.show()
print("ejemplo: animation complete")
import numpy as np
# Ejemplo de modo interactivo (ejecutar en un entorno interactivo)
print('Interactive mode:', plt.isinteractive())
# Control manual del renderizado en modo no interactivo
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() # Renderizado manual
plt.pause(0.5) # Pausar 0.5 segundos
plt.show()
print("ejemplo: animation complete")
switch_backend()
matplotlib.pyplot.switch_backend(newbackend)
switch_backend() solo se puede llamar después de la primera importación de pyplot y antes de crear cualquier Figure. Después de crear una Figure, cambiar de backend requiere usar la funcionalidad experimental.
matplotlib.use()。
Otras extensiones