现在位置: 首页 > Matplotlib 教程 > 正文

Matplotlib 工具与交互函数


Matplotlib 参考文档 Matplotlib 参考文档

这组函数提供事件处理、属性操作、鼠标交互和调试工具。

函数一览

函数功能
connect()绑定事件回调函数
disconnect()解绑事件回调函数
ginput()通过鼠标点击获取坐标
waitforbuttonpress()等待鼠标或键盘按下
findobj()查找匹配条件的 Artist
get() / setp()获取/设置 Artist 属性
getp()获取 Artist 属性(get 的别名)
get_current_fig_manager()获取当前 Figure 管理器
new_figure_manager()为 Figure 创建管理器
set_loglevel()设置日志级别
xkcd()切换为 xkcd 手绘漫画风格

事件处理 - connect() / disconnect()

matplotlib.pyplot.connect(s, func)
matplotlib.pyplot.disconnect(cid)

实例

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')

# 点击事件回调
def on_click(event):
    print(f'Clicked at: x={event.xdata:.2f}, y={event.ydata:.2f}')

# 绑定事件
cid = fig.canvas.mpl_connect('button_press_event', on_click)

plt.show()
print("runoob: click events registered")

ginput() - 鼠标选取坐标

matplotlib.pyplot.ginput(n=1, timeout=30, show_clicks=True,
    mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT,
    mouse_stop=MouseButton.MIDDLE)

实例

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() - 等待按键

matplotlib.pyplot.waitforbuttonpress(timeout=-1)

返回值:True 表示键盘按下,False 表示鼠标按下。

实例

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() - 查找 Artist

matplotlib.pyplot.findobj(o=None, match=None, include_self=False)

实例

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')

# 查找所有 Line2D 对象
lines = ax.findobj(match=Line2D)
print(f"Found {len(lines)} line objects")

# 获取特定属性
for line in lines:
    print(f"  - label: {line.get_label()}")

# 使用 get() 获取属性
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() - 属性操作

matplotlib.pyplot.get(obj, *args, **kwargs)
matplotlib.pyplot.setp(obj, *args, **kwargs)
matplotlib.pyplot.getp(obj, *args, **kwargs)

实例

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() 获取单个属性
print("line color:", plt.get(line, 'color'))

# getp() 获取多个属性
props = plt.getp(line)
print(f"line has {len(props)} properties")

# setp() 批量设置属性
plt.setp(line, color='red', linewidth=3, linestyle='--')

ax.set_title('setp() demo')
ax.legend()
plt.show()
print("runoob: properties modified via setp()")

xkcd() - 手绘漫画风格

matplotlib.pyplot.xkcd(scale=1, length=100, randomness=2)

实例

import matplotlib.pyplot as plt
import numpy as np

# 开启 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("runoob: xkcd style displayed")

set_loglevel() - 日志级别

matplotlib.pyplot.set_loglevel(level)

level 可选:'debug', 'info', 'warning', 'error', 'critical'。

实例

import matplotlib.pyplot as plt
import numpy as np

# 设置日志级别为 info(查看 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()

Matplotlib 参考文档 Matplotlib 参考文档