[ Python ] (범례 순서 변경) change legend order

2020. 2. 6. 17:47분석 Python/Visualization

728x90

legend의 순서를 조정 바꾸고 싶을 때가 있다.
쌍으로 묶고 싶은 것들이 떨어져 있었다. 이 문제를 해결하기 위해서 다음과 같은 방법으로 해결했다.

labels에서 A A 끼리 B , B 끼리... 묶고 싶었다.

legend = plt.legend(handles=handles, labels=labels, ncol=5, 
                    bbox_to_anchor=(0.9, 1.0),
                    labelspacing = 0.1, columnspacing  = 0.5,
                    fancybox=True, shadow=True,fontsize=14
          )
frame = legend.get_frame()
frame.set_linewidth(0.0)
plt.show()

하지만 그냥 하면 저렇게 떨어지게 된다.
그래서 label을 가져와서 다음과 같은 방법으로 해결했다!

handles, labels = ax.get_legend_handles_labels()
labels2 , handles2 = [] , []
for first, second , first_1 , second_1 in zip(handles[1:6] , handles[6:], labels[1:6] , labels[6:]) :
    a = [first, second]
    b = [first_1, second_1]
    handles2.extend(a)
    labels2.extend(b)
legend = plt.legend(handles=handles2, labels=labels2, ncol=5,
                    bbox_to_anchor=(0.9, 1.0),
                    labelspacing = 0.1, columnspacing  = 0.5,
                    fancybox=True, shadow=True, fontsize=14
          )
frame = legend.get_frame()
frame.set_linewidth(5.0)
frame.set_facecolor('steelblue')
plt.show()

728x90