본문 바로가기
Matplotlib 공통옵션/범례(legend)

[파이썬 matplotlib] 그래프 범례 넣기 (legend)

by 만다린망고 2022. 3. 17.
반응형

범례를 넣을 때는 legend 메소드를 사용합니다. 데이터 이름을 먼저 입력하고, 위치 옵션을 설정해주면 됩니다. 위치옵션은 loc 입니다. 입력 가능 값은 아래와 같습니다. 문자열로 입력합니다. 

best (최적위치)
upper right
upper left
upper center
lower right
lower left
lower center
center left
center right
center

아래는 예시입니다. #범례넣기 부분을 보시면 됩니다. 

import matplotlib.pyplot as plt
import pandas as pd

#데이터 생성
df1=pd.DataFrame({'X':[45,50,64,72,77],'Y':[155,165,177,187,177]})

#그래프생성
plt.plot(df1['X'],df1['Y'],color='blue',linestyle='dashed',marker='o')
plt.plot(df1['X'],df1['Y'],color='red',drawstyle='steps-post',marker='o')

#그래프 정보 설정
plt.xlim(40, 80) #x축 범위
plt.ylim(100, 200) #y축 범위
plt.xlabel('X') #x 라벨
plt.ylabel('Y') #y 라벨
plt.title("TITLE") #그래프 이름

#범례 넣기
plt.legend(('data1','data2'),loc='center right')

#그래프 출력
plt.show()

 

반응형

댓글