使用 matplotlib.widgets 的交互式控件
为了与图表交互,Matplotlib 提供 GUI 中性小部件 。小部件需要 matplotlib.axes.Axes
对象。
这是一个滑块小部件演示,用于更新正弦曲线的幅度。更新功能由滑块的 on_changed()
事件触发。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Slider
TWOPI = 2*np.pi
fig, ax = plt.subplots()
t = np.arange(0.0, TWOPI, 0.001)
initial_amp = .5
s = initial_amp*np.sin(t)
l, = plt.plot(t, s, lw=2)
ax = plt.axis([0,TWOPI,-1,1])
axamp = plt.axes([0.25, .03, 0.50, 0.02])
# Slider
samp = Slider(axamp, 'Amp', 0, 1, valinit=initial_amp)
def update(val):
# amp is the current value of the slider
amp = samp.val
# update curve
l.set_ydata(amp*np.sin(t))
# redraw canvas while idle
fig.canvas.draw_idle()
# call update function on slider value change
samp.on_changed(update)
plt.show()
https://i.stack.imgur.com/TJms6.gif 其他可用的小部件: