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 re正则表达式模块(Regular Expression)
Jul 16 Python
Python实现获取网站PR及百度权重
Jan 21 Python
Python内置函数—vars的具体使用方法
Dec 04 Python
Scrapy使用的基本流程与实例讲解
Oct 21 Python
python实现对象列表根据某个属性排序的方法详解
Jun 11 Python
学Python 3的理由和必要性
Nov 19 Python
Python hashlib模块实例使用详解
Dec 24 Python
python目标检测给图画框,bbox画到图上并保存案例
Mar 10 Python
Python实现壁纸下载与轮换
Oct 19 Python
python statsmodel的使用
Dec 21 Python
python爬虫爬取某网站视频的示例代码
Feb 20 Python
python人工智能human learn绘图可创建机器学习模型
Nov 23 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云打印类完整示例
2016/10/15 PHP
thinkPHP5项目中实现QQ第三方登录功能
2017/10/20 PHP
跨浏览器的设置innerHTML方法
2006/09/18 Javascript
js 动态为textbox添加下拉框数据源的方法
2014/04/24 Javascript
js构造函数、索引数组和属性的实现方式和使用
2014/11/16 Javascript
JavaScript中的立即执行函数表达式介绍
2015/03/15 Javascript
js实现仿阿里巴巴城市选择框效果实例
2015/06/24 Javascript
理解javascript中的原型和原型链
2015/07/30 Javascript
jquery $.trim()去除字符串空格的实现方法【附图例】
2016/03/30 Javascript
JS全局变量和局部变量最新解析
2016/06/24 Javascript
js中删除数组中的某一元素实例(无下标时)
2017/02/28 Javascript
详解通过JSON数据使用VUE.JS
2017/05/26 Javascript
JavaScript同源策略和跨域访问实例详解
2018/04/03 Javascript
taro开发微信小程序的实践
2019/05/21 Javascript
Layui实现数据表格中鼠标悬浮图片放大效果,离开时恢复原图的方法
2019/09/11 Javascript
javascript贪吃蛇游戏设计与实现
2020/09/17 Javascript
原生JS实现拖拽效果
2020/12/04 Javascript
[04:49]2014DOTA2国际邀请赛 Newbee顺利挺进总决赛 ImbaTV独家专访
2014/07/19 DOTA
[41:21]夜魇凡尔赛茶话会 第三期02:看图识人
2021/03/11 DOTA
Python实现对excel文件列表值进行统计的方法
2015/07/25 Python
Python实现针对给定单链表删除指定节点的方法
2018/04/12 Python
JavaScript实现一维数组转化为二维数组
2018/04/17 Python
判断python字典中key是否存在的两种方法
2018/08/10 Python
多个python文件调用logging模块报错误
2020/02/12 Python
pandas.DataFrame.drop_duplicates 用法介绍
2020/07/06 Python
使用sublime text3搭建Python编辑环境的实现
2021/01/12 Python
Python列表的深复制和浅复制示例详解
2021/02/12 Python
药品质量检测应届生求职信
2013/11/14 职场文书
医学生自荐信
2013/12/03 职场文书
班组长工作职责
2013/12/25 职场文书
大学生个人简历中的自我评价
2013/12/27 职场文书
2015年监理工作总结范文
2015/04/07 职场文书
2015年教育实习工作总结
2015/04/24 职场文书
初中班主任教育随笔
2015/08/15 职场文书
接触艺术对孩子学习思维有益
2019/08/06 职场文书
Python 机器学习工具包SKlearn的安装与使用
2021/05/14 Python