在 Matplotlib 中,鼠标右键移动画布的功能通常是通过设置交互模式来实现的,例如使用 mpl_connect
方法。以下是一个示例代码,展示如何在 Matplotlib 中使用 mpl_connect
方法来实现鼠标右键移动画布的功能: 文章来源地址https://www.toymoban.com/news/detail-634430.html
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
class PanCanvas:
def __init__(self, ax):
self.ax = ax
self.press = None
self.x0 = None
self.y0 = None
self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
def on_press(self, event):
if event.button == 3: # Right mouse button
self.press = event.xdata, event.ydata
self.x0 = self.ax.get_xlim()
self.y0 = self.ax.get_ylim()
def on_release(self, event):
if self.press is not None:
self.press = None
self.ax.figure.canvas.draw()
def on_motion(self, event):
if self.press is None:
return
if event.button == 3: # Right mouse button
x_press, y_press = self.press
dx = event.xdata - x_press
dy = event.ydata - y_press
self.ax.set_xlim(self.x0[0] - dx, self.x0[1] - dx)
self.ax.set_ylim(self.y0[0] - dy, self.y0[1] - dy)
self.ax.figure.canvas.draw()
def main():
# 创建一个绘图窗口和一个子图
fig, ax = plt.subplots()
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
# 绘制一些示例数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
line, = ax.plot(x, y)
# 创建 PanCanvas 对象
pan_canvas = PanCanvas(ax)
plt.show()
if __name__ == "__main__":
main()
文章来源:https://www.toymoban.com/news/detail-634430.html
到了这里,关于【Python matplotlib】鼠标右键移动画布的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!