如何在 Matplotlib 中向曲线添加光标?
若要在 Matplotlib 中向曲线添加光标,我们可以采取以下步骤 −
- 设置图形大小并调整子图之间以及子图周围的填充。
- 使用 numpy 创建 t 和 s 数据点。
- 创建一个图形和一组子图。
- 获取光标类实例,以更新绘图中的光标点。
- 在 mouse_event 中,得到鼠标当前位置的 x 和 y 数据。
- 获得 x 和 y 数据点的索引号。
- 设置 x 和 y 坐标。
- 设置文本坐标并重新绘制 agg 缓冲器和鼠标事件。
- 使用 plot() 方法绘制 t 和 s 数据点。
- 设置一些轴属性。
- 使用 show() 方法显示图形。
范例
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
class CursorClass(object):
def __init__(self, ax, x, y):
self.ax = ax
self.ly = ax.axvline(color='yellow', alpha=0.5)
self.marker, = ax.plot([0], [0], marker="o", color="red", zorder=3)
self.x = x
self.y = y
self.txt = ax.text(0.7, 0.9, '')
def mouse_event(self, event):
if event.inaxes:
x, y = event.xdata, event.ydata
indx = np.searchsorted(self.x, [x])[0]
x = self.x[indx]
y = self.y[indx]
self.ly.set_xdata(x)
self.marker.set_data([x], [y])
self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
self.txt.set_position((x, y))
self.ax.figure.canvas.draw_idle()
else:
return
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * 2 * np.pi * t)
fig, ax = plt.subplots()
cursor = CursorClass(ax, t, s)
cid = plt.connect('motion_notify_event', cursor.mouse_event)
ax.plot(t, s, lw=2, color='green')
plt.axis([0, 1, -1, 1])
plt.show()输出


广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP