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中实现迭代器(iterator)的方法示例
Jan 19 Python
Python爬虫实战之12306抢票开源
Jan 24 Python
深入了解和应用Python 装饰器 @decorator
Apr 02 Python
使用python进行广告点击率的预测的实现
Jul 04 Python
Django Form and ModelForm的区别与使用
Dec 06 Python
Django 批量插入数据的实现方法
Jan 12 Python
python字符串,元组,列表,字典互转代码实例详解
Feb 14 Python
pandas DataFrame 数据选取,修改,切片的实现
Apr 24 Python
解决Keras中CNN输入维度报错问题
Jun 29 Python
基于tensorflow for循环 while循环案例
Jun 30 Python
Python time库的时间时钟处理
May 02 Python
Python基于百度AI实现抓取表情包
Jun 27 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
PHP获取photoshop写入图片文字信息的方法
2015/03/31 PHP
php动态读取数据清除最右边距的方法
2017/04/12 PHP
浅谈PHP中类和对象的相关函数
2017/04/26 PHP
PHP Trait代码复用类与多继承实现方法详解
2019/06/17 PHP
让你的PHP,APACHE,NGINX支持大文件上传
2021/03/09 PHP
实例:尽可能写友好的Javascript代码
2006/10/09 Javascript
(推荐一个超好的JS函数库)S.Sams Lifexperience ScriptClassLib
2007/04/29 Javascript
推荐20家国外的脚本下载网站
2011/04/28 Javascript
javascript全局变量封装模块实现代码
2012/11/28 Javascript
jQuery中addClass()方法用法实例
2015/01/05 Javascript
js在指定位置增加节点函数insertBefore()用法实例
2015/01/12 Javascript
JavaScript正则表达式的分组匹配详解
2016/02/13 Javascript
node+experss实现爬取电影天堂爬虫
2016/11/20 Javascript
Jquery给当前页或者跳转后页面的导航栏添加选中后样式的实例
2016/12/08 Javascript
简单实现Vue的observer和watcher
2016/12/21 Javascript
vue组件实例解析
2017/01/10 Javascript
基于JavaScript实现窗口拖动效果
2017/01/18 Javascript
为什么要使用Vuex的介绍
2019/01/19 Javascript
vue 解决form表单提交但不跳转页面的问题
2019/10/30 Javascript
JavaScript基于面向对象实现的无缝滚动轮播示例
2020/01/17 Javascript
JavaScript实现随机点名小程序
2020/10/29 Javascript
[03:35]2018年度DOTA2最佳辅助位选手5号位-完美盛典
2018/12/17 DOTA
[58:54]EG vs RNG 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/18 DOTA
Python爬虫框架Scrapy常用命令总结
2018/07/26 Python
Python中的pathlib.Path为什么不继承str详解
2019/06/23 Python
Python基础之字符串常见操作经典实例详解
2020/02/26 Python
小 200 行 Python 代码制作一个换脸程序
2020/05/12 Python
Django之全局使用request.user.username的实例详解
2020/05/14 Python
Django使用rest_framework写出API
2020/05/21 Python
HTML5中的Web Notification桌面通知功能的实现方法
2019/07/29 HTML / CSS
法国在线药房:Shop Pharmacie
2019/11/26 全球购物
什么是数组名
2012/05/10 面试题
在求职信中如何凸显个人优势
2013/10/30 职场文书
父亲节活动策划方案
2014/08/24 职场文书
党的群众路线教育实践活动个人整改落实情况汇报
2014/10/28 职场文书
领导工作表现评语
2015/01/04 职场文书