본문 바로가기
파이썬/시각화 matplot

그래프에 설명적기-text, annotation

by Merware 2023. 5. 17.

[학습목표]
그래프의 특정 위치에 설명을 추가할 수 있다.

import pandas as pd
import matplotlib.pyplot as plt
# 그래프에 한글폰트 설정
plt.rcParams['font.family']='NanumGothic'

# 그래프에 마이너스 기호 깨지는 문제 해결
plt.rcParams['axes.unicode_minus'] = False

텍스트 추가하기

  • plt.text(x좌표, y좌표, 텍스트)
  • rotation=회전각도
  • ha : horizontal alignment
  • va : vertical alignment
  • 텍스트 상자
    bbox = {'boxstyle':상자스타일, 'fc':facecolor,'ec':edgecolor,...}
    boxstyle : 'round'/'square'
plt.plot([1,2,3,4], 'ko')
plt.text(2.1, 3, '(x:2, y:3)', ha='left', va='bottom', fontsize=12, rotation=45
        , bbox={'boxstyle':'round', 'fc':'skyblue', 'ec':'b', 'alpha':0.3})
plt.axhline(3, ls=':', alpha=0.5, lw=0.5)
plt.axvline(2, ls=':', alpha=0.5, lw=0.5)
plt.plot(2,3,'ro')
plt.show()

 

 

화살표와 텍스트 추가하기

  • plt.annotate('텍스트',xy=(화살표x,화살표y), xytext=(텍스트x,텍스트y), arrowprops=화살표속성(딕셔너리))

  • 화살표 속성
    width The width of the arrow in points
    headwidth The width of the base of the arrow head in points
    headlength The length of the arrow head in points
    shrink Fraction of total length to shrink from both ends
plt.plot([1,2,3,4], 'ko')
plt.axhline(2, color='orange', lw=0.5, alpha=0.5, ls='--')
plt.axvline(1, color='orange', lw=0.5, alpha=0.5, ls='--')
plt.plot(1,2,'ro')

plt.annotate('(x:1,y:2)', xy=(1,2), xytext=(1.5,2.5)
             , arrowprops={'width':1, 'headwidth':10, 'headlength':10, 'shrink':0.1, 'fc':'r'}
             , fontsize=12, color='r')
plt.show()