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

Seaborn histplot颜色显示异常、图例匹配错误问题求助

问题:Seaborn直方图颜色显示异常且图例不匹配

运行以下代码时,绘图中red和blue两种颜色显示异常,且图例存在颜色不匹配的情况:

import matplotlib.pyplot as plt
import seaborn as sns

maxs = [35, 31, 35, 31, 34, 30, 31, 29, 30, 33]
clrs = ['red', 'blue', 'red', 'blue', 'red', 'blue', 'blue', 'blue', 'blue', 'red']

fig, ax = plt.subplots(figsize=(8, 4))

sns.histplot(ax = ax, x = maxs, bins = "auto", discrete = True, shrink = 0.5,
             stat = "count", element = "bars", kde = False, hue = clrs) 

plt.show() 

异常的直方图

错误原因

Seaborn的hue参数设计用来接收分类变量(比如表示分组的标签),而非直接传入颜色字符串列表。当你直接传入clrs这样的颜色列表时,Seaborn会把每个颜色字符串当作一个独立分类,然后使用默认调色板为这些分类分配颜色,这就导致了你看到的颜色显示异常、图例和实际颜色不匹配的问题。

解决方案

方法一:用DataFrame整理数据+自定义调色板(推荐)

将数据整理成DataFrame,把颜色列表作为分组列,再通过palette参数指定每个分组对应的颜色:

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

maxs = [35, 31, 35, 31, 34, 30, 31, 29, 30, 33]
clrs = ['red', 'blue', 'red', 'blue', 'red', 'blue', 'blue', 'blue', 'blue', 'red']

# 将数据整理为DataFrame,把颜色作为分组列
df = pd.DataFrame({'数值': maxs, '分组': clrs})

fig, ax = plt.subplots(figsize=(8, 4))

# 指定hue为分组列,用palette映射分组到对应颜色
sns.histplot(ax=ax, x='数值', data=df, discrete=True, shrink=0.5,
             stat="count", element="bars", kde=False, hue='分组',
             palette={'red': 'red', 'blue': 'blue'})

plt.show()

方法二:手动统计计数+绘制分组条形图

如果需要直观展示每个数值下不同颜色的计数,可以手动统计后绘制分组条形图:

import matplotlib.pyplot as plt
from collections import defaultdict

maxs = [35, 31, 35, 31, 34, 30, 31, 29, 30, 33]
clrs = ['red', 'blue', 'red', 'blue', 'red', 'blue', 'blue', 'blue', 'blue', 'red']

# 统计每个数值下各颜色的出现次数
count_dict = defaultdict(lambda: {'red':0, 'blue':0})
for val, color in zip(maxs, clrs):
    count_dict[val][color] += 1

# 提取排序后的数值列表
sorted_values = sorted(count_dict.keys())
bar_width = 0.35

fig, ax = plt.subplots(figsize=(8, 4))

# 绘制红色分组条形
red_heights = [count_dict[val]['red'] for val in sorted_values]
ax.bar([x - bar_width/2 for x in range(len(sorted_values))], red_heights, 
       width=bar_width, color='red', label='red')

# 绘制蓝色分组条形
blue_heights = [count_dict[val]['blue'] for val in sorted_values]
ax.bar([x + bar_width/2 for x in range(len(sorted_values))], blue_heights, 
       width=bar_width, color='blue', label='blue')

# 设置x轴刻度
ax.set_xticks(range(len(sorted_values)))
ax.set_xticklabels(sorted_values)
ax.legend()

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:45:01