Matplotlib의 곡선에 커서를 추가하려면 다음 단계를 수행할 수 있습니다. -
- 그림 크기를 설정하고 서브플롯 사이 및 주변 여백을 조정합니다.
- t 만들기 및 numpy를 사용한 데이터 포인트
- 그림과 서브플롯 세트를 생성합니다.
- 커서 클래스 인스턴스를 가져와 플롯의 커서 포인트를 업데이트합니다.
- mouse_event에서 현재 마우스 위치의 x,y 데이터를 가져옵니다.
- x 및 y 데이터 포인트의 인덱스를 가져옵니다.
- x 및 y 위치를 설정합니다.
- 텍스트 위치를 설정하고 agg 버퍼와 마우스 이벤트를 다시 그립니다.
- 플롯 t 및 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() 출력
