Herramientas y funciones interactivas de Matplotlib
Documentación de referencia de Matplotlib
Este conjunto de funciones proporciona herramientas de manejo de eventos, operación de atributos, interacción con el ratón y depuración.
Descripción general de funciones
| Función | Descripción |
|---|---|
| connect() | Vincular función de devolución de llamada de eventos |
| disconnect() | Desvincular función de devolución de llamada de eventos |
| ginput() | Obtener coordenadas mediante clics del ratón |
| waitforbuttonpress() | Esperar a que se presione el ratón o una tecla |
| findobj() | Buscar Artist que coincidan con la condición |
| get() / setp() | Obtener/establecer atributos de Artist |
| getp() | Obtener atributos de Artist (alias de get) |
| get_current_fig_manager() | Obtener el administrador de la Figure actual |
| new_figure_manager() | Crear un administrador para Figure |
| set_loglevel() | Establecer el nivel de registro |
| xkcd() | Cambiar al estilo de cómic dibujado a mano de xkcd |
Manejo de eventos - connect() / disconnect()
matplotlib.pyplot.connect(s, func) matplotlib.pyplot.disconnect(cid)
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(np.random.randn(50).cumsum())
ax.set_title('Click anywhere on the figure')
# devolución de llamada del evento de clic
def on_click(event):
print(f'Clicked at: x={event.xdata:.2f}, y={event.ydata:.2f}')
# vincular evento
cid = fig.canvas.mpl_connect('button_press_event', on_click)
plt.show()
print("ejemplo: click events registered")
import numpy as np
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(np.random.randn(50).cumsum())
ax.set_title('Click anywhere on the figure')
# devolución de llamada del evento de clic
def on_click(event):
print(f'Clicked at: x={event.xdata:.2f}, y={event.ydata:.2f}')
# vincular evento
cid = fig.canvas.mpl_connect('button_press_event', on_click)
plt.show()
print("ejemplo: click events registered")
ginput() - seleccionar coordenadas con el ratón
matplotlib.pyplot.ginput(n=1, timeout=30, show_clicks=True,
mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT,
mouse_stop=MouseButton.MIDDLE)
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(7, 5))
ax.plot(np.arange(10), np.random.randn(10), 'o-')
ax.set_title('Click 3 points (timeout=15s)')
ax.set_xlim(-1, 10)
ax.set_ylim(-3, 3)
ax.grid(True, alpha=0.3)
print("Please click 3 points...")
points = plt.ginput(3, timeout=15, show_clicks=True)
for i, (x, y) in enumerate(points):
print(f"Point {i+1}: ({x:.2f}, {y:.2f})")
plt.show()
import numpy as np
fig, ax = plt.subplots(figsize=(7, 5))
ax.plot(np.arange(10), np.random.randn(10), 'o-')
ax.set_title('Click 3 points (timeout=15s)')
ax.set_xlim(-1, 10)
ax.set_ylim(-3, 3)
ax.grid(True, alpha=0.3)
print("Please click 3 points...")
points = plt.ginput(3, timeout=15, show_clicks=True)
for i, (x, y) in enumerate(points):
print(f"Point {i+1}: ({x:.2f}, {y:.2f})")
plt.show()
waitforbuttonpress() - esperar a que se presione una tecla
matplotlib.pyplot.waitforbuttonpress(timeout=-1)
Valor de retorno: True indica que se presionó una tecla, False indica que se presionó el ratón.
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.plot(np.sin(np.linspace(0, 10, 100)))
ax.set_title('Press any key or click mouse')
print("Waiting for button press...")
result = plt.waitforbuttonpress(timeout=10)
if result is None:
print("Timeout!")
elif result:
print("Key was pressed")
else:
print("Mouse was clicked")
plt.show()
import numpy as np
fig, ax = plt.subplots()
ax.plot(np.sin(np.linspace(0, 10, 100)))
ax.set_title('Press any key or click mouse')
print("Waiting for button press...")
result = plt.waitforbuttonpress(timeout=10)
if result is None:
print("Timeout!")
elif result:
print("Key was pressed")
else:
print("Mouse was clicked")
plt.show()
findobj() - buscar Artist
matplotlib.pyplot.findobj(o=None, match=None, include_self=False)
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6], label='Line A')
ax.plot([1, 2, 3], [1, 2, 3], label='Line B')
ax.set_title('Find Objects Demo')
# buscar todos los objetos Line2D
lines = ax.findobj(match=Line2D)
print(f"Found {len(lines)} line objects")
# obtener un atributo específico
for line in lines:
print(f" - label: {line.get_label()}")
# usar get() para obtener atributos
ax_title = ax.get_title()
print(f"Axes title: {ax_title}")
plt.show()
import numpy as np
from matplotlib.lines import Line2D
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6], label='Line A')
ax.plot([1, 2, 3], [1, 2, 3], label='Line B')
ax.set_title('Find Objects Demo')
# buscar todos los objetos Line2D
lines = ax.findobj(match=Line2D)
print(f"Found {len(lines)} line objects")
# obtener un atributo específico
for line in lines:
print(f" - label: {line.get_label()}")
# usar get() para obtener atributos
ax_title = ax.get_title()
print(f"Axes title: {ax_title}")
plt.show()
Found 2 line objects - label: Line A - label: Line B Axes title: Find Objects Demo
get() / setp() - operaciones de propiedades
matplotlib.pyplot.get(obj, *args, **kwargs) matplotlib.pyplot.setp(obj, *args, **kwargs) matplotlib.pyplot.getp(obj, *args, **kwargs)
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(layout='constrained')
line, = ax.plot([0, 1], [0, 1], label='test')
# get() obtiene un solo atributo
print("line color:", plt.get(line, 'color'))
# getp() obtiene múltiples atributos
props = plt.getp(line)
print(f"line has {len(props)} properties")
# setp() establece atributos en lote
plt.setp(line, color='red', linewidth=3, linestyle='--')
ax.set_title('setp() demo')
ax.legend()
plt.show()
print("ejemplo: properties modified via setp()")
import numpy as np
fig, ax = plt.subplots(layout='constrained')
line, = ax.plot([0, 1], [0, 1], label='test')
# get() obtiene un solo atributo
print("line color:", plt.get(line, 'color'))
# getp() obtiene múltiples atributos
props = plt.getp(line)
print(f"line has {len(props)} properties")
# setp() establece atributos en lote
plt.setp(line, color='red', linewidth=3, linestyle='--')
ax.set_title('setp() demo')
ax.legend()
plt.show()
print("ejemplo: properties modified via setp()")
xkcd() - estilo de cómic dibujado a mano
matplotlib.pyplot.xkcd(scale=1, length=100, randomness=2)
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
# activar el estilo de dibujo a mano de xkcd
with plt.xkcd():
fig, ax = plt.subplots(figsize=(8, 5))
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')
ax.set_title('XKCD-style Plot')
ax.set_xlabel('Time')
ax.set_ylabel('Amplitude')
ax.legend()
ax.annotate('This is peak!',
xy=(np.pi/2, 1), xytext=(2, 1.3),
arrowprops=dict(arrowstyle='->'))
plt.show()
print("ejemplo: xkcd style displayed")
import numpy as np
# activar el estilo de dibujo a mano de xkcd
with plt.xkcd():
fig, ax = plt.subplots(figsize=(8, 5))
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')
ax.set_title('XKCD-style Plot')
ax.set_xlabel('Time')
ax.set_ylabel('Amplitude')
ax.legend()
ax.annotate('This is peak!',
xy=(np.pi/2, 1), xytext=(2, 1.3),
arrowprops=dict(arrowstyle='->'))
plt.show()
print("ejemplo: xkcd style displayed")
set_loglevel() - nivel de registro
matplotlib.pyplot.set_loglevel(level)
level opcional: 'debug', 'info', 'warning', 'error', 'critical'.
Ejemplo
import matplotlib.pyplot as plt
import numpy as np
# establecer el nivel de registro a info (ver información interna de Matplotlib)
plt.set_loglevel('info')
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Debugging with loglevel')
plt.show()
import numpy as np
# establecer el nivel de registro a info (ver información interna de Matplotlib)
plt.set_loglevel('info')
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Debugging with loglevel')
plt.show()
Otras extensiones