matplotlib绘制鼠标的十字光标的实现(内置方式)


Posted in Python onJanuary 06, 2021

相对于echarts等基于JavaScript的图表库,matplotlib的交互能力相对较差。
在实际应用中,我们经常想使用十字光标来定位数据坐标,matplotlib内置提供支持。

官方示例

matplotlib提供了官方示例https://matplotlib.org/gallery/widgets/cursor.html

from matplotlib.widgets import Cursor
import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, facecolor='#FFFFCC')

x, y = 4*(np.random.rand(2, 100) - .5)
ax.plot(x, y, 'o')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)

# Set useblit=True on most backends for enhanced performance.
cursor = Cursor(ax, useblit=True, color='red', linewidth=2)

plt.show()

matplotlib绘制鼠标的十字光标的实现(内置方式)

原理

由源码可知,实现十字光标的关键在于widgets模块中的Cursor类。
class matplotlib.widgets.Cursor(ax, horizOn=True, vertOn=True, useblit=False, **lineprops)

  • ax:参数类型matplotlib.axes.Axes,即需要添加十字光标的子图。
  • horizOn:布尔值,是否显示十字光标中的横线,默认值为显示。
  • vertOn:布尔值,是否显示十字光标中的竖线,默认值为显示。
  • useblit:布尔值,是否使用优化模式,默认值为否,优化模式需要后端支持。
  • **lineprops:十字光标线形属性, 参见axhline函数支持的属性,https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.axhline.html#matplotlib.axes.Axes.axhline

简化案例

光标改为灰色竖虚线,线宽为1。

from matplotlib.widgets import Cursor
import matplotlib.pyplot as plt

ax = plt.gca()
cursor = Cursor(ax, horizOn=False, vertOn= True, useblit=False, color='grey', linewidth=1,linestyle='--')
plt.show()

matplotlib绘制鼠标的十字光标的实现(内置方式)

## 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

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

Python 相关文章推荐
Python字典操作简明总结
Apr 13 Python
python实现bucket排序算法实例分析
May 04 Python
Python正则抓取网易新闻的方法示例
Apr 21 Python
python中利用await关键字如何等待Future对象完成详解
Sep 07 Python
python可视化实现KNN算法
Oct 16 Python
Pytorch基本变量类型FloatTensor与Variable用法
Jan 08 Python
如何打包Python Web项目实现免安装一键启动的方法
May 21 Python
基于python和flask实现http接口过程解析
Jun 15 Python
python时间序列数据转为timestamp格式的方法
Aug 03 Python
python爬虫 requests-html的使用
Nov 30 Python
Python用Jira库来操作Jira
Dec 28 Python
python+selenium自动化实战携带cookies模拟登陆微博
Jan 19 Python
java字符串格式化输出实例讲解
Jan 06 #Python
matplotlib 画动态图以及plt.ion()和plt.ioff()的使用详解
Jan 05 #Python
查找适用于matplotlib的中文字体名称与实际文件名对应关系的方法
Jan 05 #Python
微软开源最强Python自动化神器Playwright(不用写一行代码)
Jan 05 #Python
Python读取ini配置文件传参的简单示例
Jan 05 #Python
matplotlib实现数据实时刷新的示例代码
Jan 05 #Python
Matplotlib配色之Colormap详解
Jan 05 #Python
You might like
完美解决dedecms中的[html][/html]和[code][/code]问题
2007/03/20 PHP
php Smarty 字符比较代码
2011/02/27 PHP
php pdo oracle中文乱码的快速解决方法
2016/05/16 PHP
php实现文件与16进制相互转换的方法示例
2017/02/16 PHP
PHP+AJAX 投票器功能
2017/11/11 PHP
浅谈PHP SHA1withRSA加密生成签名及验签
2019/03/18 PHP
js操作时间(年-月-日 时-分-秒 星期几)
2010/06/20 Javascript
扩展javascript的Date方法实现代码(prototype)
2010/11/20 Javascript
jQuery中创建实例与原型继承揭秘
2011/12/21 Javascript
jquery获取table中的某行全部td的内容方法
2013/03/08 Javascript
jQuery中prepend()方法用法实例
2014/12/25 Javascript
nodeJs链接Mysql做增删改查的简单操作
2017/02/04 NodeJs
原生JavaScript实现AJAX、JSONP
2017/02/07 Javascript
webpack构建react多页面应用详解
2017/09/15 Javascript
vue 路由页面之间实现用手指进行滑动的方法
2018/02/23 Javascript
js如何实现元素曝光上报
2019/08/07 Javascript
javascript sort()对数组中的元素进行排序详解
2019/10/13 Javascript
jQuery实现form表单基于ajax无刷新提交方法实例代码
2019/11/04 jQuery
Python面向对象编程中的类和对象学习教程
2015/03/30 Python
python下MySQLdb用法实例分析
2015/06/08 Python
使用python实现unix2dos和dos2unix命令的例子
2019/08/13 Python
Python使用APScheduler实现定时任务过程解析
2019/09/11 Python
Python操作qml对象过程详解
2019/09/26 Python
Django异步任务线程池实现原理
2019/12/17 Python
python 在sql语句中使用%s,%d,%f说明
2020/06/06 Python
Python3.7安装PyQt5 运行配置Pycharm的详细教程
2020/10/15 Python
2014年党务公开实施方案
2014/02/27 职场文书
航海技术专业毕业生求职信
2014/04/06 职场文书
群众路线剖析材料怎么写
2014/10/09 职场文书
放弃继承权公证书
2015/01/23 职场文书
颐和园的导游词
2015/01/30 职场文书
大学毕业生自我鉴定范文
2019/06/21 职场文书
2019年最新借条范本!
2019/07/08 职场文书
解决numpy数组互换两行及赋值的问题
2021/04/17 Python
深入理解以DEBUG方式线程的底层运行原理
2021/06/21 Java/Android
Mysql将字符串按照指定字符分割的正确方法
2022/05/30 MySQL