기록하는삶

[파이썬/Python] 데이터 시각화 _ x,y 축과 평행한 선, annotate 추가하기 본문

AI/데이터 시각화

[파이썬/Python] 데이터 시각화 _ x,y 축과 평행한 선, annotate 추가하기

mingchin 2022. 3. 23. 21:09
728x90
반응형
fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(111, aspect=1)

i = 13

ax.scatter(x=student['math score'], y=student['reading score'],
           c='lightgray',
           alpha=0.9, zorder=5)
    
ax.scatter(x=student['math score'][i], y=student['reading score'][i],
           c='tomato',
           alpha=1, zorder=10)    
    
ax.set_xlim(-3, 102)
ax.set_ylim(-3, 102)

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

ax.set_xlabel('Math Score')
ax.set_ylabel('Reading Score')

ax.set_title('Score Relation') 

# x축과 평행한 선
ax.plot([-3, student['math score'][i]], [student['reading score'][i]]*2,
        color='gray', linestyle='--',
        zorder=8)

# y축과 평행한 선
ax.plot([student['math score'][i]]*2, [-3, student['reading score'][i]],
       color='gray', linestyle='--',
       zorder=8)

bbox = dict(boxstyle="round", fc='wheat', pad=0.2)
arrowprops = dict(
    arrowstyle="->")

ax.annotate(text=f'This is #{i} Studnet',
            # 가리킬 지점
            xy=(student['math score'][i], student['reading score'][i]),
            # 텍스트 위치 따로 지정
            xytext=[80, 40],
            bbox=bbox,
            arrowprops=arrowprops,
            zorder=9
           )

plt.show()

위 예시 코드로 아래와 같은 그림을 그릴 수 있다. 축과 평행한 선을 그리기 위해 ax.plot([시작점],[끝점])을 지정해준다. 또한 dict() 형식으로 arrowprops를 저장한 뒤, ax.annotate를 통해 특정 위치를 화살표로 가리키게 할 수 있다. bbox를 통해 원하는 형태로 텍스트를 추가할 수 있고, zorder로 해당 annotate의 layer에서의 위치를 결정할 수 있다.(앞으로 가져오기, 뒤로 보내기 등의 효과)

또 다른 축에 평행한 선을 그리는 방법으로는 plt.axhline()과 plt.axvline()이 있다.

sns.lineplot(x = xx_, y = yy_)
plt.xticks(rotation=90)
plt.axhline(y=np.mean(yy_), color='r', linewidth=1, linestyle='--')
plt.axvline(x = 100, color = 'y')
plt.show()

 

728x90
반응형