Python库matplotlib之十一
- 事件处理
- 滚动事件
- figure/axes进入和离开事件
事件处理
滚动事件
下列程序运行时,滚动鼠标的滚轮,on_scroll函数被调用,依据滚轮的滚动方向,参数w被加1,或减1。
参数w改变,引起sin波形变化。
import matplotlib.pyplot as plt
import numpy as npclass sin_curve:MAX_W = 20def __init__(self, fig, ax):self.fig = figself.ax = axself.w = 1x = np.linspace(0, 5 * np.pi, 1000)y = np.sin(x)self.line, = self.ax.plot(x, y)def on_scroll(self, event):increment = 1 if event.button == 'up' else -1self.w += incrementif self.w <= 0:self.w = sin_curve.MAX_Welif self.w > sin_curve.MAX_W:self.w = 1x = np.linspace(0, 10 * np.pi, 1000)y = np.sin(self.w * x)self.ax.set_title('w = ' + str(self.w))self.line.set_xdata(x)self.line.set_ydata(y)self.fig.canvas.draw()if __name__ == "__main__":fig, ax = plt.subplots()sin_waveform = sin_curve(fig, ax)fig.canvas.mpl_connect('scroll_event', sin_waveform.on_scroll)plt.show()
程序运行屏幕输出
figure/axes进入和离开事件
下列程序通过处理figure和Axes进入和离开事件,控制sin函数的波形显示。
当鼠标进入Axes,特定的Axes中, timer控制sin的相位角,引起波形变化。
import matplotlib.pyplot as plt
import numpy as npclass fig_axes():def __init__(self, axs):self.timer = fig.canvas.new_timer(interval=100)self.timer.add_callback(self.timer_cb, axs)self.inc = 1self.ax = Noneself.canvas = Noneself.x = np.linspace(0, 10 * np.pi, 100)self.y = np.sin(self.x)def on_enter_axes(self, event):self.ax = event.inaxes;self.line, = self.ax.plot(self.x, self.y)event.inaxes.patch.set_facecolor('yellow')event.canvas.draw()self.canvas = event.canvasdef on_leave_axes(self, event):event.inaxes.patch.set_facecolor('white')self.line, = self.ax.plot(self.x, self.y)event.inaxes.patch.set_facecolor('yellow')event.canvas.draw()self.ax = Nonedef on_enter_figure(self, event):event.canvas.figure.patch.set_facecolor('red')event.canvas.draw()self.timer.start()def on_leave_figure(self, event):event.canvas.figure.patch.set_facecolor('white')event.canvas.draw()self.timer.stop()def timer_cb(self, axs):if self.ax == None:returnself.ax.clear()self.inc += 1self.x = np.linspace(0, 10 * np.pi, 100)self.y = np.sin(self.x + self.inc)self.ax.plot(self.x, self.y)self.canvas.draw()if __name__ == "__main__":fig, axs = plt.subplots(1, 2)fig.suptitle('mouse hover over figure or Axes to trigger events')fig_axes_1 = fig_axes(axs)fig.canvas.mpl_connect('figure_enter_event', fig_axes_1.on_enter_figure)fig.canvas.mpl_connect('figure_leave_event', fig_axes_1.on_leave_figure)fig.canvas.mpl_connect('axes_enter_event', fig_axes_1.on_enter_axes)fig.canvas.mpl_connect('axes_leave_event', fig_axes_1.on_leave_axes)plt.show()