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正常时间和unix时间戳相互转换的方法
Apr 23 Python
Python排序搜索基本算法之插入排序实例分析
Dec 11 Python
python实现神经网络感知器算法
Dec 20 Python
python代码实现ID3决策树算法
Dec 20 Python
python3+PyQt5实现自定义分数滑块部件
Apr 24 Python
Python 调用 zabbix api的方法示例
Jan 06 Python
Django接收照片储存文件的实例代码
Mar 07 Python
用python写爬虫简单吗
Jul 28 Python
Django debug为True时,css加载失败的解决方案
Apr 24 Python
python process模块的使用简介
May 14 Python
Python办公自动化之Excel(中)
May 24 Python
浅谈Python数学建模之线性规划
Jun 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:风雨欲来 路在何方?
2006/10/09 PHP
php并发对MYSQL造成压力的解决方法
2013/02/21 PHP
php使用array_rand()函数从数组中随机选择一个或多个元素
2014/04/28 PHP
php发送与接收流文件的方法
2015/02/11 PHP
PHP魔术方法的使用示例
2015/06/23 PHP
基于win2003虚拟机中apache服务器的访问
2017/08/01 PHP
PHP实现的折半查找算法示例
2017/12/19 PHP
JQuery Ajax 跨域访问的解决方案
2010/03/12 Javascript
浅谈Javascript事件处理程序的几种方式
2012/06/27 Javascript
JS在textarea光标处插入文本的小例子
2013/03/22 Javascript
浅析js中取绝对值的2种方法
2013/07/09 Javascript
js表单中选择框值的获取及表单的序列化
2015/12/17 Javascript
VueRouter导航守卫用法详解
2017/12/25 Javascript
详解JavaScript中的强制类型转换
2019/04/15 Javascript
vue+moment实现倒计时效果
2019/08/26 Javascript
基于ant design日期控件使用_仅月份的操作
2020/10/27 Javascript
Python使用MySQLdb for Python操作数据库教程
2014/10/11 Python
python中requests爬去网页内容出现乱码问题解决方法介绍
2017/10/25 Python
用十张图详解TensorFlow数据读取机制(附代码)
2018/02/06 Python
pandas 时间格式转换的实现
2019/07/06 Python
window环境pip切换国内源(pip安装异常缓慢的问题)
2019/12/31 Python
tensorflow 保存模型和取出中间权重例子
2020/01/24 Python
Python实现链表反转的方法分析【迭代法与递归法】
2020/02/22 Python
python高阶函数map()和reduce()实例解析
2020/03/16 Python
给同事的道歉信
2014/01/11 职场文书
网络工程师职业规划
2014/02/10 职场文书
养成教育经验材料
2014/05/26 职场文书
我爱家乡演讲稿
2014/09/12 职场文书
会计试用期自我评价怎么写
2014/09/18 职场文书
护士个人总结范文
2015/02/13 职场文书
幼师辞职信范文
2015/02/27 职场文书
2016年全国助残日活动总结
2016/04/01 职场文书
研究生毕业登记表的自我鉴定范文
2019/07/15 职场文书
还在手动盖楼抽奖?教你用Python实现自动评论盖楼抽奖(一)
2021/06/07 Python
美元符号 $
2022/02/17 杂记
阿里云k8s服务升级时502错误 springboot项目应用
2022/04/09 Servers