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实现dnspod自动更新dns解析的方法
Feb 14 Python
对python append 与浅拷贝的实例讲解
May 04 Python
Python实现base64编码的图片保存到本地功能示例
Jun 22 Python
Random 在 Python 中的使用方法
Aug 09 Python
python实现beta分布概率密度函数的方法
Jul 08 Python
详解Python 4.0 预计推出的新功能
Jul 26 Python
TensorFlow索引与切片的实现方法
Nov 20 Python
Django框架反向解析操作详解
Nov 28 Python
后端开发使用pycharm的技巧(推荐)
Mar 27 Python
Python基于xlutils修改表格内容过程解析
Jul 28 Python
python 自动识别并连接串口的实现
Jan 19 Python
Python如何telnet到网络设备
Feb 18 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
火车头discuz6.1 完美采集的php接口文件
2009/09/13 PHP
yii实现创建验证码实例解析
2014/07/31 PHP
JSON两种结构之对象和数组的理解
2016/07/19 PHP
JavaScript函数、方法、对象代码
2008/10/29 Javascript
JavaScript 继承的实现
2009/07/09 Javascript
Javascript学习笔记 delete运算符
2011/09/13 Javascript
javascript实现动态侧边栏代码
2014/02/19 Javascript
JavaScript 数组中最大最小值
2016/06/05 Javascript
JS正则表达式修饰符global(/g)用法分析
2016/12/27 Javascript
利用Query+bootstrap和js两种方式实现日期选择器
2017/01/10 Javascript
JavaScript函数柯里化原理与用法分析
2017/03/31 Javascript
Bootstrap模态框插件使用详解
2017/05/11 Javascript
vue-cli webpack 引入jquery的方法
2018/01/10 jQuery
Angular学习教程之RouterLink花式跳转
2018/05/03 Javascript
原生JS生成指定位数的验证码
2020/10/28 Javascript
[02:52]2014DOTA2西雅图国际邀请赛 CIS战队巡礼
2014/07/07 DOTA
[45:14]Optic vs VP 2018国际邀请赛淘汰赛BO3 第二场 8.24
2018/08/25 DOTA
Django在win10下的安装并创建工程
2017/11/20 Python
python中字典按键或键值排序的实现代码
2019/08/27 Python
pytorch实现建立自己的数据集(以mnist为例)
2020/01/18 Python
在tensorflow中实现屏蔽输出的log信息
2020/02/04 Python
python实现飞机大战游戏(pygame版)
2020/10/26 Python
tensorflow将图片保存为tfrecord和tfrecord的读取方式
2020/02/17 Python
python自动生成sql语句的脚本
2021/02/24 Python
基于tensorflow __init__、build 和call的使用小结
2021/02/26 Python
CSS3 background-image颜色渐变的实现代码
2018/09/13 HTML / CSS
苹果美国官方商城:Apple美国
2016/08/24 全球购物
英国在线花园中心:You Garden
2018/06/03 全球购物
PUMA澳大利亚官方网站:德国运动品牌
2018/10/19 全球购物
材料工程专业毕业生求职信
2014/03/04 职场文书
公司周年庆活动方案
2014/08/25 职场文书
医院护士见习期自我鉴定
2014/09/15 职场文书
学校运动会广播稿范文
2014/10/02 职场文书
党的群众路线教育实践活动领导班子整改措施
2014/10/28 职场文书
歌咏比赛主持词
2015/06/29 职场文书
2015年公司中秋节致辞
2015/07/31 职场文书