You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Seaborn传入ndarray列表时图例手柄顺序为何颠倒?

多列直方图的图例顺序问题(Seaborn)

当使用Seaborn绘制多列数据的直方图时:

  • 传入pandas DataFrame数据时,图例显示顺序正常
  • 传入ndarray列表时,Seaborn生成的图例手柄顺序会出现颠倒

示例代码

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

x1 = np.random.normal(100, 25, 100)
x2 = np.random.normal(200, 25, 100)
x3 = np.random.normal(300, 25, 100)

fig, axs = plt.subplots(1, 2, figsize=(18, 8))

# 传入DataFrame,图例显示正常
df = pd.DataFrame(np.array([x1,x2,x3]).T, columns= ['x1', 'x2', 'x3'])
sns.histplot(df, bins=30, color=['r','g', 'b'], ax=axs[0])

# 传入ndarray列表,图例顺序颠倒
sns.histplot([x1,x2,x3] , bins=30, color=['r','g', 'b'], ax=axs[1])
axs[1].legend(['x1','x2','x3'])

plt.show()

修复方法

直接从坐标轴获取已生成的图例手柄再传入legend()方法,即可恢复正常顺序:

axs[1].legend(axs[1].get_legend().legendHandles, ['x1','x2','x3'])

内容的提问来源于stack exchange,提问作者Tsahi Asher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:15:03