python.matplotlib实现手动鼠标移动坐标点

01 操作动画

  • 随意拖动任一点,任意运动
    在这里插入图片描述

02 关键代码

  • 编程:python 3.6
  • 运行环境:Pycharm
  • 只展示部分关键代码,需要源码的见文末链接
  • 关键:一定要注意能不能运动,由于坐标轴的设置区间不同,offset的偏差值,一定要对应好。否则,鼠标无法识别图中的点,造成无法移动的假象。
'''
设置:单点的动画移动
'''
    def __init__(self):
        # 创建figure(绘制面板)、创建图表(axes)
        self.fig,self.ax = plt.subplots()
        # 设置标题
        self.ax.set_title('Click and drag a point to move it')
        # 设置坐标轴范围
        self.ax.set_xlim((-2, 4))
        self.ax.set_ylim((-2, 4))
        # 设置初始值
        self.x = [1,2]
        self.y = [1,2]
        # 绘制2D的动画line
        self.line = Line2D(self.x, self.y, ls="",
                           marker='o', markerfacecolor='r',
                           animated=True)
        self.ax.add_line(self.line)
        # 标志值设为none
        self._ind = None
        # 设置画布,方便后续画布响应事件
        canvas = self.fig.canvas
        canvas.mpl_connect('draw_event', self.draw_callback)
        canvas.mpl_connect('button_press_event', self.button_press_callback)
        canvas.mpl_connect('button_release_event', self.button_release_callback)
        canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
        self.canvas = canvas
        plt.grid()
        plt.show()


    def get_ind_under_point(self, event):
        'get the index of the vertex under point if within epsilon tolerance'
        # 在公差允许的范围内,求出鼠标点下顶点坐标的数值
        xt,yt = np.array(self.x),np.array(self.y)
        d = np.sqrt((xt-event.xdata)**2 + (yt-event.ydata)**2)
        indseq = np.nonzero(np.equal(d, np.amin(d)))[0]
        ind = indseq[0]
        # 如果在公差范围内,则返回ind的值
        if d[ind] >=self.offset:
            ind = None
        return ind

    # 鼠标移动的事件
    def motion_notify_callback(self, event):
        'on mouse movement'
        if not self.showverts: return
        if self._ind is None: return
        if event.inaxes is None: return
        if event.button != 1: return
        # 更新数据
        x,y = event.xdata, event.ydata
        self.x[self._ind] = x
        self.y[self._ind] = y
        # 根据更新的数值,重新绘制图形
        self.line = Line2D(self.x, self.y, ls="",
                           marker='o', markerfacecolor='r',
                           animated=True)
        self.ax.add_line(self.line)
        # 恢复背景
        self.canvas.restore_region(self.background)
        self.ax.draw_artist(self.line)
        self.canvas.blit(self.ax.bbox)

03 源码分享

  • 源码已经上传到我的上传资料
https://download.csdn.net/download/kyrie001/11227186

辛苦研究两天的成果,如果帮到你,希望点个赞。

  • 21
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值