如何反转Seaborn水平堆叠柱状图的图例顺序?
问题描述
我使用Python的Seaborn库编写了生成水平堆叠柱状图的代码:
sns.set_style('white') ax = sns.histplot( data=temp, y='tmp', weights='Weight', hue=field, multiple='stack', palette='viridis', shrink=0.75 ) ax.set_xlabel('Weight') ax.set_ylabel('{}_{}'.format(df, attribute)) ax.set_title('plot distribution') sns.move_legend(ax, loc='upper left', bbox_to_anchor=(1, 0.97)) sns.despine() plt.tight_layout() plt.show()
希望反转图例顺序,让10.0位于顶部、0.0位于底部(倒序时间顺序),但尝试以下代码后仅移除了图例,未实现反转:
handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')
解决方法
方法一:在histplot中指定hue_order(推荐)
直接控制分类的显示顺序,让图表堆叠逻辑和图例顺序同步反转,避免图例与图表内容错位:
# 获取field列的唯一值并反转顺序 reverse_order = temp[field].unique()[::-1] sns.set_style('white') ax = sns.histplot( data=temp, y='tmp', weights='Weight', hue=field, multiple='stack', palette='viridis', shrink=0.75, hue_order=reverse_order # 新增参数指定倒序 ) ax.set_xlabel('Weight') ax.set_ylabel('{}_{}'.format(df, attribute)) ax.set_title('plot distribution') sns.move_legend(ax, loc='upper left', bbox_to_anchor=(1, 0.97)) sns.despine() plt.tight_layout() plt.show()
方法二:修正手动反转图例的代码
因sns.move_legend会干扰图例状态,需先移除默认图例,再手动添加反转后的版本:
sns.set_style('white') ax = sns.histplot( data=temp, y='tmp', weights='Weight', hue=field, multiple='stack', palette='viridis', shrink=0.75 ) ax.set_xlabel('Weight') ax.set_ylabel('{}_{}'.format(df, attribute)) ax.set_title('plot distribution') # 移除原有默认图例 ax.get_legend().remove() # 获取手柄和标签并反转 handles, labels = ax.get_legend_handles_labels() # 添加反转后的图例,保持原标题和位置 ax.legend(handles[::-1], labels[::-1], title=field, loc='upper left', bbox_to_anchor=(1, 0.97)) sns.despine() plt.tight_layout() plt.show()
注意将图例标题设为原field名称,而非硬编码的'Line'。
内容的提问来源于stack exchange,提问作者LostinSpatialAnalysis
相关产品推荐
相关产品推荐

