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解析网页源代码中的115网盘链接实例
Sep 30 Python
python正则表达式之作业计算器
Mar 18 Python
Tensorflow 自带可视化Tensorboard使用方法(附项目代码)
Feb 10 Python
python 重定向获取真实url的方法
May 11 Python
python实现字符串和字典的转换
Sep 29 Python
Python实现连接MySql数据库及增删改查操作详解
Apr 16 Python
详解Python静态网页爬取获取高清壁纸
Apr 23 Python
利用python3 的pygame模块实现塔防游戏
Dec 30 Python
tensorflow安装成功import tensorflow 出现问题
Apr 16 Python
Python+PyQt5实现灭霸响指功能
May 25 Python
python 装饰器的基本使用
Jan 13 Python
python实现Nao机器人的单目测距
Sep 04 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
How do I change MySQL timezone?
2008/03/26 PHP
PHP 伪静态隐藏传递参数名的四种方法
2010/02/22 PHP
php从右向左/从左向右截取字符串的实现方法
2011/11/28 PHP
基于php伪静态的实现详细介绍
2013/04/28 PHP
php调用C代码的实现方法
2014/03/11 PHP
PHP工厂模式简单实现方法示例
2018/05/23 PHP
PHP实现从PostgreSQL数据库检索数据分页显示及根据条件查找数据示例
2018/06/09 PHP
php实现对文件压缩简单的方法
2019/09/29 PHP
js浮点数精确计算(加、减、乘、除)
2013/12/26 Javascript
Get中文乱码IE浏览器Get中文乱码解决方案
2013/12/26 Javascript
JavaScript在IE和FF下的兼容性问题
2014/05/19 Javascript
JavaScript立即执行函数的三种不同写法
2014/09/05 Javascript
javascript 数组操作详解
2015/01/29 Javascript
jQuery Validate表单验证深入学习
2015/12/18 Javascript
JS组件中bootstrap multiselect两大组件较量
2016/01/26 Javascript
js一维数组、多维数组和对象的混合使用方法
2016/04/03 Javascript
node.js发送邮件email的方法详解
2017/01/06 Javascript
Bootstrap3下拉菜单的实现
2017/02/22 Javascript
vue.js中过滤器的使用教程
2017/06/08 Javascript
JavaScript 判断对象中是否有某属性的常用方法
2018/06/14 Javascript
JS获取指定月份的天数两种实现方法
2018/06/22 Javascript
详解webpack引用jquery(第三方模块)的三种办法
2019/08/21 jQuery
python遍历文件夹并删除特定格式文件的示例
2014/03/05 Python
python刷投票的脚本实现代码
2014/11/08 Python
python查看文件大小和文件夹内容的方法
2019/07/08 Python
python脚本执行CMD命令并返回结果的例子
2019/08/14 Python
如何使用html5与css3完成google涂鸦动画
2012/12/16 HTML / CSS
美国艺术和工艺品商店:Hobby Lobby
2020/12/09 全球购物
程序员机试试题汇总
2012/03/07 面试题
简短的公司员工自我评价分享
2013/11/13 职场文书
小学教师先进事迹材料
2014/12/15 职场文书
2015年护士节活动总结
2015/02/10 职场文书
成品仓管员岗位职责
2015/04/01 职场文书
前台接待员岗位职责
2015/04/15 职场文书
一文了解JavaScript用Element Traversal新属性遍历子元素
2021/11/27 Javascript
电频谱管理的原则是什么
2022/02/18 无线电