欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > Python库matplotlib之十一

Python库matplotlib之十一

2024/10/23 2:43:28 来源:https://blog.csdn.net/IT_Beijing_BIT/article/details/143063182  浏览:    关键词:Python库matplotlib之十一

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com