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中的闭包详细介绍和实例
Nov 21 Python
python遍历数组的方法小结
Apr 30 Python
python字符类型的一些方法小结
May 16 Python
python中的随机函数小结
Jan 27 Python
基于python的多进程共享变量正确打开方式
Apr 28 Python
使用Python编写Prometheus监控的方法
Oct 15 Python
Python数据可视化库seaborn的使用总结
Jan 15 Python
基于python的ini配置文件操作工具类
Apr 24 Python
python GUI库图形界面开发之PyQt5拖放控件实例详解
Feb 25 Python
Django怎么在admin后台注册数据库表
Nov 14 Python
2020年10款优秀的Python第三方库,看看有你中意的吗?
Jan 12 Python
python爬虫如何解决图片验证码
Feb 14 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 一个页面执行时间类代码
2010/03/05 PHP
单一index.php实现PHP任意层级文件夹遍历(Zjmainstay原创)
2012/07/31 PHP
PHP echo,print,printf,sprintf函数之间的区别与用法详解
2013/11/27 PHP
php 使用GD库为页面增加水印示例代码
2014/03/24 PHP
使用配置类定义Codeigniter全局变量
2014/06/12 PHP
PHP使用json_encode函数时不转义中文的解决方法
2014/11/12 PHP
表单提交错误后返回内容消失问题的解决方法(PHP网站)
2015/10/20 PHP
Laravel 5.4因特殊字段太长导致migrations报错的解决
2017/10/22 PHP
JQuery入门—编写一个简单的JQuery应用案例
2013/01/03 Javascript
JS模块与命名空间的介绍
2013/03/22 Javascript
鼠标滑过出现预览的大图提示效果
2014/02/26 Javascript
jquery mobile的触控点击事件会多次触发问题的解决方法
2014/05/08 Javascript
extjs每个组件要设置唯一的ID否则会出错
2014/06/15 Javascript
解析Node.js基于模块和包的代码部署方式
2016/02/16 Javascript
js实现ctrl+v粘贴上传图片(兼容chrome、firefox、ie11)
2016/03/09 Javascript
Bootstrap和Java分页实例第二篇
2016/12/23 Javascript
jQuery实现Table表格隔行变色及高亮显示当前选择行效果示例
2017/02/14 Javascript
BootStrap导航栏问题记录
2017/07/31 Javascript
JS判断数组那点事
2017/10/10 Javascript
AngularJs ng-change事件/指令的用法小结
2017/11/01 Javascript
详解swipe使用及竖屏页面滚动方法
2018/06/28 Javascript
Vue 3.0 前瞻Vue Function API新特性体验
2019/08/12 Javascript
使用Python从有道词典网页获取单词翻译
2016/07/03 Python
python字符串,数值计算
2016/10/05 Python
如何表示python中的相对路径
2020/07/08 Python
anaconda3安装及jupyter环境配置全教程
2020/08/24 Python
css3制作彩色边线3d立体按钮的示例(css3按钮)
2014/05/06 HTML / CSS
野兽派官方旗舰店:THE BEAST 野兽派
2016/08/05 全球购物
暑期实习鉴定
2013/12/16 职场文书
关于热爱祖国的演讲稿
2014/05/04 职场文书
2014年设备管理工作总结
2014/11/26 职场文书
2015年安全生产目标责任书
2015/01/29 职场文书
个人总结怎么写
2015/02/26 职场文书
观看建国大业观后感
2015/06/01 职场文书
数学备课组工作总结
2015/08/12 职场文书
2016寒假社会实践心得体会范文
2015/10/09 职场文书