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

Python中按Hue与类别自定义箱线图/柱状图配色的实现方法

实现方案

你可以直接通过seaborn绘图接口的palette参数自定义分组配色,以下提供箱线图、分组柱状图两种实现:

方案1:箱线图+自定义配色

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

# 测试数据
test = pd.DataFrame([[2021, 'female', 3], [2021, 'male', 1], [2021, 'female', 6],
                    [2021, 'female', 3], [2021, 'male', 4], [2021, 'female', 10],
                    [2020, 'female', 2], [2020, 'male', 9], [2020, 'male', 7],
                    [2020, 'female', 1], [2020, 'male', 5], [2020, 'male', 8]
                   ], columns=['Year', 'category', 'value'])

plt.figure(figsize=(10,6))
# 自定义配色字典,key对应hue字段的取值,value为对应颜色(支持十六进制、标准颜色名)
custom_palette = {
    2020: "#FF8C8C",
    2021: "#6495ED"
}
g = sns.boxplot(y='value', x='category', data=test, hue='Year', palette=custom_palette)
g.set_xticklabels(g.get_xmajorticklabels(), fontsize = 12)
plt.xlabel('类别', fontsize=12)
plt.ylabel('数值', fontsize=12)
plt.legend(title='年份', fontsize=12)
plt.show()

方案2:分组柱状图+自定义配色

如果需要用柱状图展示,可直接替换绘图接口,支持自动计算聚合值和误差棒:

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

test = pd.DataFrame([[2021, 'female', 3], [2021, 'male', 1], [2021, 'female', 6],
                    [2021, 'female', 3], [2021, 'male', 4], [2021, 'female', 10],
                    [2020, 'female', 2], [2020, 'male', 9], [2020, 'male', 7],
                    [2020, 'female', 1], [2020, 'male', 5], [2020, 'male', 8]
                   ], columns=['Year', 'category', 'value'])

plt.figure(figsize=(10,6))
custom_palette = {
    2020: "#FF8C8C",
    2021: "#6495ED"
}
# ci='sd'表示用标准差作为误差棒,也可以修改为其他置信区间
g = sns.barplot(y='value', x='category', data=test, hue='Year', palette=custom_palette, edgecolor='black', ci='sd')
g.set_xticklabels(g.get_xmajorticklabels(), fontsize = 12)
plt.xlabel('类别', fontsize=12)
plt.ylabel('平均数值', fontsize=12)
plt.legend(title='年份', fontsize=12)
plt.show()

你可以根据需求调整custom_palette里的色值,适配自己的配色要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:15:06