Matplotlib Tools and Interactive Functions


Matplotlib 参考文档Matplotlib Reference Documentation

This set of functions provides event handling, property operations, mouse interaction, and debugging tools.

Function Overview

FunctionDescription
connect()Bind event callback function
disconnect()Unbind event callback function
ginput()Get coordinates via mouse click
waitforbuttonpress()Wait for mouse or keyboard press
findobj()Find Artist matching conditions
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 Figure
set_loglevel()Set log 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("example: click events registered")

ginput() - Mouse Coordinate Selection

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 was pressed, False indicates a mouse button was pressed.

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

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 get 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 Operations

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() gets a single property
print("line color:", plt.get(line, 'color'))

# getp() gets multiple properties
props = plt.getp(line)
print(f"line has {len(props)} properties")

# setp() sets multiple properties at once
plt.setp(line, color='red', linewidth=3, linestyle='--')

ax.set_title('setp() demo')
ax.legend()
plt.show()
print("example: 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("example: xkcd style displayed")

set_loglevel() - Log Level

matplotlib.pyplot.set_loglevel(level)

level options: 'debug', 'info', 'warning', 'error', 'critical'.

Example

import matplotlib.pyplot as plt
import numpy as np

# Set log level to info (view Matplotlib internal information)
plt.set_loglevel('info')

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Debugging with loglevel')

plt.show()

Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions