【Python matplotlib】鼠标右键移动画布

在 Matplotlib 中,鼠标右键移动画布的功能通常是通过设置交互模式来实现的,例如使用 mpl_connect 方法。以下是一个示例代码,展示如何在 Matplotlib 中使用 mpl_connect 方法来实现鼠标右键移动画布的功能:

python 复制代码
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()
相关推荐
张3蜂1 天前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring
无小道1 天前
Qt——事件简单介绍
开发语言·前端·qt
devmoon1 天前
在 Paseo 测试网上获取 Coretime:On-demand 与 Bulk 的完整实操指南
开发语言·web3·区块链·测试用例·智能合约·solidity
皮卡丘不断更1 天前
手搓本地 RAG:我用 Python 和 Spring Boot 给 AI 装上了“实时代码监控”
人工智能·spring boot·python·ai编程
kylezhao20191 天前
C# 中的 SOLID 五大设计原则
开发语言·c#
爱打代码的小林1 天前
基于 MediaPipe 实现实时面部关键点检测
python·opencv·计算机视觉
极客小云1 天前
【ComfyUI API 自动化利器:comfyui_xy Python 库使用详解】
网络·python·自动化·comfyui
凡人叶枫1 天前
C++中输入、输出和文件操作详解(Linux实战版)| 从基础到项目落地,避坑指南
linux·服务器·c语言·开发语言·c++
闲人编程1 天前
Elasticsearch搜索引擎集成指南
python·elasticsearch·搜索引擎·jenkins·索引·副本·分片
春日见1 天前
车辆动力学:前后轮车轴
java·开发语言·驱动开发·docker·计算机外设