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

Seaborn histplot堆叠柱状图与图例颜色不匹配问题求助

Seaborn histplot 颜色与图例不匹配问题解决

你使用Seaborn绘制带hue参数的堆叠柱状图时,出现了柱状图颜色与图例颜色不匹配的问题——运行代码无报错,但颜色映射错位。你的代码如下:

# my 'new_ba', 'route', and 'sentiment' are defined

plt.figure(figsize = (10,5))
plt.title('Sentiment of Route')
colors = {'Positive': 'green', 'Neutral': 'blue', 'Negative': 'red'}

sns.histplot(data=new_ba, x='route', hue='sentiment', palette=colors.values())
plt.xticks(rotation=45, ha='right')

plt.savefig('problem.png')
plt.show()

问题原因

问题出在palette=colors.values()这一行:Seaborn会按照hue变量(即sentiment)的类别顺序分配调色板颜色,但colors.values()返回的颜色顺序不一定和sentiment列的实际类别顺序一致,导致颜色与图例的对应关系错位。

解决方法

直接将颜色字典colors传给palette参数,Seaborn会自动根据字典的键匹配对应的sentiment类别,确保颜色与图例完全对应:

# my 'new_ba', 'route', and 'sentiment' are defined

plt.figure(figsize = (10,5))
plt.title('Sentiment of Route')
colors = {'Positive': 'green', 'Neutral': 'blue', 'Negative': 'red'}

# 直接传入颜色字典,替代colors.values()
sns.histplot(data=new_ba, x='route', hue='sentiment', palette=colors)
plt.xticks(rotation=45, ha='right')

plt.savefig('problem.png')
plt.show()

内容的提问来源于stack exchange,提问作者EG Film

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 06:16:08