ในการเพิ่มเคอร์เซอร์ให้กับเส้นโค้งใน Matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้ -
- กำหนดขนาดรูปและปรับช่องว่างภายในระหว่างและรอบๆ แผนผังย่อย
- สร้าง t และ s จุดข้อมูลโดยใช้ตัวเลข
- สร้างร่างและชุดแผนย่อย
- รับอินสแตนซ์คลาสเคอร์เซอร์ เพื่ออัปเดตจุดเคอร์เซอร์บนโครงเรื่อง
- ใน mouse_event รับข้อมูล x และ y ของตำแหน่งปัจจุบันของเมาส์
- รับดัชนีจุดข้อมูล x และ y
- กำหนดตำแหน่ง x และ y
- ตั้งค่าตำแหน่งข้อความและวาดเหตุการณ์บัฟเฟอร์ agg และเมาส์ใหม่
- พล็อต t และ s จุดข้อมูลโดยใช้ plot() วิธีการ
- กำหนดคุณสมบัติของแกน
- หากต้องการแสดงรูป ให้ใช้ 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() ผลลัพธ์
