脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - matplotlib绘制鼠标的十字光标的实现(内置方式)

matplotlib绘制鼠标的十字光标的实现(内置方式)

2021-08-22 00:14mighty13 Python

这篇文章主要介绍了matplotlib绘制鼠标的十字光标的实现(内置方式),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

相对于echarts等基于JavaScript的图表库,matplotlib的交互能力相对较差。
在实际应用中,我们经常想使用十字光标来定位数据坐标,matplotlib内置提供支持。

官方示例

matplotlib提供了官方示例https://matplotlib.org/gallery/widgets/cursor.html

  1. from matplotlib.widgets import Cursor
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. # Fixing random state for reproducibility
  6. np.random.seed(19680801)
  7.  
  8. fig = plt.figure(figsize=(8, 6))
  9. ax = fig.add_subplot(111, facecolor='#FFFFCC')
  10.  
  11. x, y = 4*(np.random.rand(2, 100) - .5)
  12. ax.plot(x, y, 'o')
  13. ax.set_xlim(-2, 2)
  14. ax.set_ylim(-2, 2)
  15.  
  16. # Set useblit=True on most backends for enhanced performance.
  17. cursor = Cursor(ax, useblit=True, color='red', linewidth=2)
  18.  
  19. 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。

  1. from matplotlib.widgets import Cursor
  2. import matplotlib.pyplot as plt
  3.  
  4. ax = plt.gca()
  5. cursor = Cursor(ax, horizOn=False, vertOn= True, useblit=False, color='grey', linewidth=1,linestyle='--')
  6. plt.show()

matplotlib绘制鼠标的十字光标的实现(内置方式)

## Cursor类源码

  1. class Cursor(AxesWidget):
  2. """
  3. A crosshair cursor that spans the axes and moves with mouse cursor.
  4.  
  5. For the cursor to remain responsive you must keep a reference to it.
  6.  
  7. Parameters
  8. ----------
  9. ax : `matplotlib.axes.Axes`
  10. The `~.axes.Axes` to attach the cursor to.
  11. horizOn : bool, default: True
  12. Whether to draw the horizontal line.
  13. vertOn : bool, default: True
  14. Whether to draw the vertical line.
  15. useblit : bool, default: False
  16. Use blitting for faster drawing if supported by the backend.
  17.  
  18. Other Parameters
  19. ----------------
  20. **lineprops
  21. `.Line2D` properties that control the appearance of the lines.
  22. See also `~.Axes.axhline`.
  23.  
  24. Examples
  25. --------
  26. See :doc:`/gallery/widgets/cursor`.
  27. """
  28.  
  29. def __init__(self, ax, horizOn=True, vertOn=True, useblit=False,
  30. **lineprops):
  31. AxesWidget.__init__(self, ax)
  32.  
  33. self.connect_event('motion_notify_event', self.onmove)
  34. self.connect_event('draw_event', self.clear)
  35.  
  36. self.visible = True
  37. self.horizOn = horizOn
  38. self.vertOn = vertOn
  39. self.useblit = useblit and self.canvas.supports_blit
  40.  
  41. if self.useblit:
  42. lineprops['animated'] = True
  43. self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops)
  44. self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops)
  45.  
  46. self.background = None
  47. self.needclear = False
  48.  
  49. def clear(self, event):
  50. """Internal event handler to clear the cursor."""
  51. if self.ignore(event):
  52. return
  53. if self.useblit:
  54. self.background = self.canvas.copy_from_bbox(self.ax.bbox)
  55. self.linev.set_visible(False)
  56. self.lineh.set_visible(False)
  57.  
  58. def onmove(self, event):
  59. """Internal event handler to draw the cursor when the mouse moves."""
  60. if self.ignore(event):
  61. return
  62. if not self.canvas.widgetlock.available(self):
  63. return
  64. if event.inaxes != self.ax:
  65. self.linev.set_visible(False)
  66. self.lineh.set_visible(False)
  67.  
  68. if self.needclear:
  69. self.canvas.draw()
  70. self.needclear = False
  71. return
  72. self.needclear = True
  73. if not self.visible:
  74. return
  75. self.linev.set_xdata((event.xdata, event.xdata))
  76.  
  77. self.lineh.set_ydata((event.ydata, event.ydata))
  78. self.linev.set_visible(self.visible and self.vertOn)
  79. self.lineh.set_visible(self.visible and self.horizOn)
  80.  
  81. self._update()
  82.  
  83. def _update(self):
  84. if self.useblit:
  85. if self.background is not None:
  86. self.canvas.restore_region(self.background)
  87. self.ax.draw_artist(self.linev)
  88. self.ax.draw_artist(self.lineh)
  89. self.canvas.blit(self.ax.bbox)
  90. else:
  91. self.canvas.draw_idle()
  92. return False

到此这篇关于matplotlib绘制鼠标的十字光标的实现(内置方式)的文章就介绍到这了,更多相关matplotlib 十字光标内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/mighty13/article/details/112136779

延伸 · 阅读

精彩推荐