Matplotlib Tools and Interactive Functions |
Matplotlib Reference Documentation
This set of functions provides event handling, property manipulation, mouse interaction, and debugging tools.
Function Overview
| Function | Functionality |
|---|---|
| connect() | Bind an event callback function |
| disconnect() | Unbind an event callback function |
| ginput() | Get coordinates via mouse clicks |
| waitforbuttonpress() | Wait for mouse or keyboard press |
| findobj() | Find Artist objects matching given criteria |
| get() / setp() | Get / set Artist properties |
| getp() | Get Artist properties (alias for get()) |
| get_current_fig_manager() | Get the current Figure manager |
| new_figure_manager() | Create a manager for a Figure |
| set_loglevel() | Set logging level |
| xkcd() | Switch to xkcd hand-drawn comic style |
Event Handling β connect() / disconnect()
matplotlib.pyplot.connect(s, func) matplotlib.pyplot.disconnect(cid)
Example
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')
# Click event callback
def on_click(event):
print(f'Clicked at: x={event.xdata:.2f}, y={event.ydata:.2f}')
# Bind event
cid = fig.canvas.mpl_connect('button_press_event', on_click)
plt.show()
print("tutorial: click events registered")
ginput() β Mouse Selection of Coordinates
matplotlib.pyplot.ginput(n=1, timeout=30, show_clicks=True, mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT, mouse_stop=MouseButton.MIDDLE)
Example
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()
waitforbuttonpress() β Wait for Key Press
matplotlib.pyplot.waitforbuttonpress(timeout=-1)
Return value: True indicates a key press; False indicates a mouse click.
Example
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()
findobj() β Find Artist Objects
matplotlib.pyplot.findobj(o=None, match=None, include_self=False)
Example
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')
# Find all Line2D objects
lines = ax.findobj(match=Line2D)
print(f"Found {len(lines)} line objects")
# Get specific properties
for line in lines:
print(f" - label: {line.get_label()}")
# Use get() to retrieve properties
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() β Property Manipulation
matplotlib.pyplot.get(obj, *args, **kwargs)
matplotlib.pyplot.setp(obj, *args, **kwargs)
matplotlib.pyplot.getp(obj, *args, **kwargs)
Example
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() retrieve a single property
print("line color:", plt.get(line, 'color'))
# getp() retrieve multiple properties
props = plt.getp(line)
print(f"line has {len(props)} properties")
# setp() batch set properties
plt.setp(line, color='red', linewidth=3, linestyle='--')
ax.set_title('setp() demo')
ax.legend()
plt.show()
print("tutorial: properties modified via setp()")
xkcd() β Hand-drawn Comic Style
matplotlib.pyplot.xkcd(scale=1, length=100, randomness=2)
Example
import matplotlib.pyplot as plt
import numpy as np
# Enable xkcd hand-drawn style
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("tutorial: xkcd style displayed")
set_loglevel() β Logging Level
matplotlib.pyplot.set_loglevel(level)
level options: 'debug', 'info', 'warning', 'error', 'critical'.
Example
import matplotlib.pyplot as plt
import numpy as np
# Set logging level to 'info' (to view Matplotlib internal messages)
plt.set_loglevel('info')
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Debugging with loglevel')
plt.show()
YouTip