使用 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 其他可用的小部件: