파이썬/그래프 그리기

python(vscode)/그래프에 커서 표시하기#2/데이터 보여주기

gongdol 2022. 12. 3. 15:22
300x250

지난글에이어 그래프 커서움직일때마다 데이터를 그려보자.

 

1. 코드 작성하자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets
import numpy as np
 
# 1. 커서 움질일때 데이터 보여주는 코드 정의 
class SnaptoCursor(object):
    def __init__(self, ax, x, y):
        self.ax = ax
        self.ly = ax.axvline(color='k', alpha=0.2)  # the vert line
        self.marker, = ax.plot([0],[0], marker="o", color="crimson", zorder=3
        self.x = x
        self.y = y
        self.txt = ax.text(0.70.9'')
 
    def mouse_move(self, event):
        if not event.inaxes: return
        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()
 
# 2. 그래프 그릴 데이터 생성
= np.arange(0.01.00.01)
= np.sin(2*2*np.pi*t)
 
# 3. 그래프 및 커서 정의 
fig, ax = plt.subplots()
cursor = SnaptoCursor(ax, t, s)
cid =  plt.connect('motion_notify_event', cursor.mouse_move)
 
# 4. 그래프 그리기
ax.plot(t, s,)
plt.axis([01-11])
plt.show()
cs

 

 

2. 결과

   -. 결과를 보면 오른쪽위에 있는 데이터와 그래프 옆에 있는 데이터가 다르다.

   -. 그이유는 마우스가 x위치 기준으로 커서라인이 움직이기때문이다. (즉 마우스 위치가 빨간색 점에 있지않고 다른위치에 있다 현재, 이미지에는 나타나지 않았다)

 

300x250