matplotlib绘制鼠标的十字光标的实现(自定义方式,官方实例)


Posted in Python onJanuary 10, 2021

matplotlib在widgets模块提供Cursor类用于支持十字光标的生成。另外官方还提供了自定义十字光标的实例。

widgets模块Cursor类源码

class Cursor(AxesWidget):
  """
  A crosshair cursor that spans the axes and moves with mouse cursor.

  For the cursor to remain responsive you must keep a reference to it.

  Parameters
  ----------
  ax : `matplotlib.axes.Axes`
    The `~.axes.Axes` to attach the cursor to.
  horizOn : bool, default: True
    Whether to draw the horizontal line.
  vertOn : bool, default: True
    Whether to draw the vertical line.
  useblit : bool, default: False
    Use blitting for faster drawing if supported by the backend.

  Other Parameters
  ----------------
  **lineprops
    `.Line2D` properties that control the appearance of the lines.
    See also `~.Axes.axhline`.

  Examples
  --------
  See :doc:`/gallery/widgets/cursor`.
  """

  def __init__(self, ax, horizOn=True, vertOn=True, useblit=False,
         **lineprops):
    AxesWidget.__init__(self, ax)

    self.connect_event('motion_notify_event', self.onmove)
    self.connect_event('draw_event', self.clear)

    self.visible = True
    self.horizOn = horizOn
    self.vertOn = vertOn
    self.useblit = useblit and self.canvas.supports_blit

    if self.useblit:
      lineprops['animated'] = True
    self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops)
    self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops)

    self.background = None
    self.needclear = False

  def clear(self, event):
    """Internal event handler to clear the cursor."""
    if self.ignore(event):
      return
    if self.useblit:
      self.background = self.canvas.copy_from_bbox(self.ax.bbox)
    self.linev.set_visible(False)
    self.lineh.set_visible(False)
    
  def onmove(self, event):
    """Internal event handler to draw the cursor when the mouse moves."""
    if self.ignore(event):
      return
    if not self.canvas.widgetlock.available(self):
      return
    if event.inaxes != self.ax:
      self.linev.set_visible(False)
      self.lineh.set_visible(False)

      if self.needclear:
        self.canvas.draw()
        self.needclear = False
      return
    self.needclear = True
    if not self.visible:
      return
    self.linev.set_xdata((event.xdata, event.xdata))

    self.lineh.set_ydata((event.ydata, event.ydata))
    self.linev.set_visible(self.visible and self.vertOn)
    self.lineh.set_visible(self.visible and self.horizOn)

    self._update()

  def _update(self):
    if self.useblit:
      if self.background is not None:
        self.canvas.restore_region(self.background)
      self.ax.draw_artist(self.linev)
      self.ax.draw_artist(self.lineh)
      self.canvas.blit(self.ax.bbox)
    else:
      self.canvas.draw_idle()
    return False

自定义十字光标实现

简易十字光标实现

首先在 Cursor类的构造方法__init__中,构造了十字光标的横线、竖线和坐标显示;然后在on_mouse_move方法中,根据事件数据更新横竖线和坐标显示,最后在调用时,通过mpl_connect方法绑定on_mouse_move方法和鼠标移动事件'motion_notify_event'。

import matplotlib.pyplot as plt
import numpy as np


class Cursor:
  """
  A cross hair cursor.
  """
  def __init__(self, ax):
    self.ax = ax
    self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
    self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
    # text location in axes coordinates
    self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)

  def set_cross_hair_visible(self, visible):
    need_redraw = self.horizontal_line.get_visible() != visible
    self.horizontal_line.set_visible(visible)
    self.vertical_line.set_visible(visible)
    self.text.set_visible(visible)
    return need_redraw

  def on_mouse_move(self, event):
    if not event.inaxes:
      need_redraw = self.set_cross_hair_visible(False)
      if need_redraw:
        self.ax.figure.canvas.draw()
    else:
      self.set_cross_hair_visible(True)
      x, y = event.xdata, event.ydata
      # update the line positions
      self.horizontal_line.set_ydata(y)
      self.vertical_line.set_xdata(x)
      self.text.set_text('x=%1.2f, y=%1.2f' % (x, y))
      self.ax.figure.canvas.draw()


x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)

fig, ax = plt.subplots()
ax.set_title('Simple cursor')
ax.plot(x, y, 'o')
cursor = Cursor(ax)
#关键部分,绑定鼠标移动事件处理
fig.canvas.mpl_connect('motion_notify_event', cursor.on_mouse_move)
plt.show()

优化十字光标实现

在简易实现中,每次鼠标移动时,都会重绘整个图像,这样效率比较低。
在优化实现中,每次鼠标移动时,只重绘光标和坐标显示,背景图像不再重绘。

import matplotlib.pyplot as plt
import numpy as np


class BlittedCursor:
  """
  A cross hair cursor using blitting for faster redraw.
  """
  def __init__(self, ax):
    self.ax = ax
    self.background = None
    self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
    self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
    # text location in axes coordinates
    self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
    self._creating_background = False
    ax.figure.canvas.mpl_connect('draw_event', self.on_draw)

  def on_draw(self, event):
    self.create_new_background()

  def set_cross_hair_visible(self, visible):
    need_redraw = self.horizontal_line.get_visible() != visible
    self.horizontal_line.set_visible(visible)
    self.vertical_line.set_visible(visible)
    self.text.set_visible(visible)
    return need_redraw

  def create_new_background(self):
    if self._creating_background:
      # discard calls triggered from within this function
      return
    self._creating_background = True
    self.set_cross_hair_visible(False)
    self.ax.figure.canvas.draw()
    self.background = self.ax.figure.canvas.copy_from_bbox(self.ax.bbox)
    self.set_cross_hair_visible(True)
    self._creating_background = False

  def on_mouse_move(self, event):
    if self.background is None:
      self.create_new_background()
    if not event.inaxes:
      need_redraw = self.set_cross_hair_visible(False)
      if need_redraw:
        self.ax.figure.canvas.restore_region(self.background)
        self.ax.figure.canvas.blit(self.ax.bbox)
    else:
      self.set_cross_hair_visible(True)
      # update the line positions
      x, y = event.xdata, event.ydata
      self.horizontal_line.set_ydata(y)
      self.vertical_line.set_xdata(x)
      self.text.set_text('x=%1.2f, y=%1.2f' % (x, y))

      self.ax.figure.canvas.restore_region(self.background)
      self.ax.draw_artist(self.horizontal_line)
      self.ax.draw_artist(self.vertical_line)
      self.ax.draw_artist(self.text)
      self.ax.figure.canvas.blit(self.ax.bbox)


x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)

fig, ax = plt.subplots()
ax.set_title('Blitted cursor')
ax.plot(x, y, 'o')
blitted_cursor = BlittedCursor(ax)
fig.canvas.mpl_connect('motion_notify_event', blitted_cursor.on_mouse_move)
plt.show()

捕捉数据十字光标实现

在前面的两种实现中,鼠标十字光标可以随意移动。在本实现中,十字光标只会出现在离鼠标x坐标最近的数据点上。

import matplotlib.pyplot as plt
import numpy as np


class SnappingCursor:
  """
  A cross hair cursor that snaps to the data point of a line, which is
  closest to the *x* position of the cursor.

  For simplicity, this assumes that *x* values of the data are sorted.
  """
  def __init__(self, ax, line):
    self.ax = ax
    self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
    self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
    self.x, self.y = line.get_data()
    self._last_index = None
    # text location in axes coords
    self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)

  def set_cross_hair_visible(self, visible):
    need_redraw = self.horizontal_line.get_visible() != visible
    self.horizontal_line.set_visible(visible)
    self.vertical_line.set_visible(visible)
    self.text.set_visible(visible)
    return need_redraw

  def on_mouse_move(self, event):
    if not event.inaxes:
      self._last_index = None
      need_redraw = self.set_cross_hair_visible(False)
      if need_redraw:
        self.ax.figure.canvas.draw()
    else:
      self.set_cross_hair_visible(True)
      x, y = event.xdata, event.ydata
      index = min(np.searchsorted(self.x, x), len(self.x) - 1)
      if index == self._last_index:
        return # still on the same data point. Nothing to do.
      self._last_index = index
      x = self.x[index]
      y = self.y[index]
      # update the line positions
      self.horizontal_line.set_ydata(y)
      self.vertical_line.set_xdata(x)
      self.text.set_text('x=%1.2f, y=%1.2f' % (x, y))
      self.ax.figure.canvas.draw()


x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)

fig, ax = plt.subplots()
ax.set_title('Snapping cursor')
line, = ax.plot(x, y, 'o')
snap_cursor = SnappingCursor(ax, line)
fig.canvas.mpl_connect('motion_notify_event', snap_cursor.on_mouse_move)
plt.show()

参考资料

https://www.matplotlib.org.cn/gallery/misc/cursor_demo_sgskip.html

到此这篇关于matplotlib绘制鼠标的十字光标的实现(自定义方式,官方实例)的文章就介绍到这了,更多相关matplotlib鼠标十字光标 内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python做文本按行去重的实现方法
Oct 19 Python
Python 描述符(Descriptor)入门
Nov 20 Python
Python subprocess模块详细解读
Jan 29 Python
python批量查询、汉字去重处理CSV文件
May 31 Python
python cs架构实现简单文件传输
Mar 20 Python
python使用folium库绘制地图点击框
Sep 21 Python
python 快速把超大txt文件转存为csv的实例
Oct 26 Python
python opencv 简单阈值算法的实现
Aug 04 Python
Python获取时间范围内日期列表和周列表的函数
Aug 05 Python
tensorflow通过模型文件,使用tensorboard查看其模型图Graph方式
Jan 23 Python
在django admin中配置搜索域是一个外键时的处理方法
May 20 Python
Python在centos7.6上安装python3.9的详细教程(默认python版本为2.7.5)
Oct 15 Python
解决selenium+Headless Chrome实现不弹出浏览器自动化登录的问题
Jan 09 #Python
用Python自动清理电脑内重复文件,只要10行代码(自动脚本)
Jan 09 #Python
selenium+headless chrome爬虫的实现示例
Jan 08 #Python
plt.figure()参数使用详解及运行演示
Jan 08 #Python
matplotlib绘制多子图共享鼠标光标的方法示例
Jan 08 #Python
利用python查看数组中的所有元素是否相同
Jan 08 #Python
Python爬虫自动化获取华图和粉笔网站的错题(推荐)
Jan 08 #Python
You might like
PHP学习笔记之二 php入门知识
2011/01/12 PHP
深入理解PHP原理之错误抑制与内嵌HTML分析
2011/05/02 PHP
既简单又安全的PHP验证码 附调用方法
2016/06/02 PHP
laravel框架模型中非静态方法也能静态调用的原理分析
2019/11/23 PHP
javascript 火狐(firefox)不显示本地图片问题解决
2008/07/05 Javascript
jquery封装的对话框简单实现
2013/07/21 Javascript
jquery使用jxl插件导出excel示例
2014/04/14 Javascript
Extjs Label的 fieldLabel和html属性值对齐的方法
2014/06/15 Javascript
JavaScript fontcolor方法入门实例(按照指定的颜色来显示字符串)
2014/10/17 Javascript
javascript手工制作悬浮菜单
2015/02/12 Javascript
JavaScript操作URL的相关内容集锦
2015/10/29 Javascript
用director.js实现前端路由使用实例
2017/01/27 Javascript
JavaScript正则获取地址栏中参数的方法
2017/03/02 Javascript
微信小程序搜索组件wxSearch实例详解
2017/06/08 Javascript
vuejs实现本地数据的筛选分页功能思路详解
2017/11/15 Javascript
手写Node静态资源服务器的实现方法
2018/03/20 Javascript
详解angular2.x创建项目入门指令
2018/10/11 Javascript
koa-router路由参数和前端路由的结合详解
2019/05/19 Javascript
jquery实现Ajax请求的几种常见方式总结
2019/05/28 jQuery
layer弹出层显示在top顶层的方法
2019/09/11 Javascript
详解vue3.0 diff算法的使用(超详细)
2020/07/01 Javascript
jQuery 添加元素和删除元素的方法
2020/07/15 jQuery
[04:09]2014DOTA2国际邀请赛Ti西雅图 历届冠军相继出局 BBC综述今日比赛
2014/07/20 DOTA
python访问抓取网页常用命令总结
2017/04/11 Python
Python3 适合初学者学习的银行账户登录系统实例
2017/08/08 Python
Python cookbook(数据结构与算法)通过公共键对字典列表排序算法示例
2018/03/15 Python
Python处理CSV与List的转换方法
2018/04/19 Python
python 对类的成员函数开启线程的方法
2019/01/22 Python
python scatter散点图用循环分类法加图例
2019/03/19 Python
python BlockingScheduler定时任务及其他方式的实现
2019/09/19 Python
Python模块相关知识点小结
2020/03/09 Python
西安众合通用.net笔试题
2013/03/18 面试题
电大毕业生自我鉴定
2014/04/10 职场文书
学生实习证明范文
2014/09/28 职场文书
MySQL系列之十五 MySQL常用配置和性能压力测试
2021/07/02 MySQL
Win10 heic文件怎么打开 ? Win10 heic文件打开教程
2022/04/06 数码科技