본문 바로가기

언어 꿀Tip/Python 꿀tip!

07_01_41. 그래프 범례 삽입 (graph legend), 여러 line 겹쳐 그리기

여러개 plot이 존재할 때, 범례 추가하기

from matplotlib import pyplot as plt
import matplotlib.pylab as plt2

plt2.rcParams["figure.figsize"] = (15,4)   # plot 크기 조절

fig, ax0 = plt.subplots()
ax0.set_xlabel('date')
ax0.set_ylabel('amt')  # 메인 축 label (축이름)
ax0.set_ylim(1000000,2400000)  # 메인 축 범위 조절

line0 = ax0.plot( df_tot['datecd'], df_tot['amt'], color='black' , label='tot')

# 2중축 추가
ax1 = ax0.twinx()
ax1.set_ylabel('amt(1)')  # sub 보조 축 label (축이름)
# ax1.set_ylim(10000,70000)  # sub 보조 축 범위 조절

# line 추가
line1 = ax1.plot( df_tot['datecd'], df_tot['amt_01'] , color='blue' , label='01')
line2 = ax1.plot( df_tot['datecd'], df_tot['amt_02'] , color='orange', label='02')
line3 = ax1.plot( df_tot['datecd'], df_tot['amt_03'] , color='green', label='03')
line4 = ax1.plot( df_tot['datecd'], df_tot['amt_04'] , color='purple', label='04')

lines = line0 +line1+line2+line3+line4

# 범례, legend 추가
labels = [l.get_label() for l in lines]
ax0.legend(lines, labels, loc='upper right')

plt.show()