본문 바로가기
Computer/python

[seaborn] histplot legend 순서 뒤집는 법, 바꾸는 법

by injeolmialmond 2022. 10. 20.

stacked countplot을 그릴 때 가장 쉽게 구현할 수 있는 방법이 seaborn의 histplot에 hue 파타미터를 지정해주는 것인데요,

matplotlib이나 seaborn에서 제공하는 다른 플랏 객체들과는 달리 seaborn의 histplot은 legend의 순서를 쉽게 바꿀 수 없습니다. 

그런데 기본적으로 제공하는 legend의 순서가 stack이 된 순서와는 역순이라는 문제점이 있습니다.

legend와 bar의 순서가 뒤바뀌어 있어서 눈으로 보고 해석하기에 상당히 헷갈립니다.

 

matplotlib legend order reverse

change plot legend order 

reverse legend

legend order seaborn ..

등등 다양한 검색어로 검색해 보았지만 뚜렷한 해결방안이 없었습니다.

 

https://stackoverflow.com/questions/22263807/how-is-order-of-items-in-matplotlib-legend-determined

 

How is order of items in matplotlib legend determined?

I am having to reorder items in a legend, when I don't think I should have to. I try: from pylab import * clf() ax=gca() ht=ax.add_patch(Rectangle((1,1),1,1,color='r',label='Top',alpha=.1)) h1=ax.b...

stackoverflow.com

위 질문과 답변을 보고 그대로 따라해보았을 때도, histplot 객체에  .get_legend_handles_labels() 를 붙이면 handles, labels에 모두 빈 리스트가 나오게 됩니다.

 

대신 찾게 된 것이 아래에 있는 질문 답변이었는데요,

https://stackoverflow.com/questions/66346542/customizing-legend-in-seaborn-histplot-subplots

 

Customizing legend in Seaborn histplot subplots

I am trying to generate a figure with 4 subplots, each of which is a Seaborn histplot. The figure definition lines are: fig,axes=plt.subplots(2,2,figsize=(6.3,7),sharex=True,sharey=True) (ax1,ax2),...

stackoverflow.com

 

아래 코드로 histplot의 legend 순서를 역순으로 변경할 수 있습니다.

import seaborn as sns
p = sns.histplot(데이터, x=컬럼명, hue=컬럼명, ..)
legend_names = [레전드에 들어갈 각 문자열 (내가 원하는 순서)]
legend = p.get_legend()
handles = legend.legendHandles
legend.remove()
p.legend(handles[::-1], legend_names)

 

혹은 만약 역순이 아니라 본인이 원하는 순서가 있다면 가장 마지막 줄을 바꿀 수 있겠습니다.

handles_order = [3,2,1,4,0] # 만약 레전드에 다섯 개가 들어간다면
p.legend([handles[idx] for idx in handles_order], legend_names)

 

 

이렇게 빨간색이 가장 위로, 노랑색이 가장 아래로 오는 bar의 순서에 맞추어 legend에 표기되는 label의 순서도 바꿀 수 있습니다.

댓글