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

seaborn pairplot调整类别顺序时保持类别对应颜色固定

问题描述

我使用tab10_r调色板绘制seaborn.pairplot图,效果如下:
类别顺序为['2','1','0']的绘图效果

若将同一份绘图数据的类别顺序调整为[0,1,2]后再绘制相同图表,效果如下:
类别顺序为['0','1','2']的绘图效果

需求:对同一份数据绘制3张类别排序不同的图表时,所有图中标签与颜色的对应关系固定不变:Label 0始终为绿色、Label 1始终为紫色、Label 2始终为灰色,不会随类别顺序调整发生变化。

当前使用的代码如下:

import seaborn as sns
import pandas as pd

data = {'Feat1': [-46.220314, -23.80669, -42.092365, -35.29639, -37.075096, -42.8849, -32.3057, -24.469942, -97.89892, -81.96325, -78.41986, -100.68544, -87.05412, -64.121056, -94.504845, -61.951996, -108.19452, -97.4037, -92.641335, -199.18787, -137.5976, -208.0035, -108.225975, -121.29299],
        'Feat2': [22.862856, 20.536781, 25.680704, 21.709473, 22.347767, 28.03802, 26.568039, 27.005375, -0.38156664, 0.1821717, -6.766374, -4.5810957, -2.9231584, -3.7892206, -0.9999217, -8.960198, 13.909201, 22.897585, 22.10624, 3.3090565, 6.795896, -1.33229, 14.341716, 18.274035],
        'Feat3': [-6.1573067, -5.015675, -5.0092897, -4.160352, -3.860426, -7.8572545, -9.47018, -9.301921, 6.4163384, -1.2870358, 0.8001185, 1.6977689, 6.817379, -0.283514, 3.2884297, -1.5915259, 0.6966458, -2.8488266, -3.5110545, -2.5994794, 1.6793671, -3.2078092, 1.02891, 2.2891548],
        'Feat4': [5.6060414, 4.2216353, 5.665794, 5.578346, 5.6953945, 3.3361, 3.4532788, 4.3995037, 7.234347, 4.703838, 0.83444935, 1.8801615, 5.4460077, 6.3084154, 6.881124, 5.6160254, -1.956591, 1.4105041, 2.467166, 4.0802555, 2.2256763, 1.5177402, -1.8651972, 2.3360753],
        'Labels': [2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]}
df = pd.DataFrame(data)
df1 = df.copy()
df2 = df.copy()

df1['Labels'] = df1['Labels'].astype(str)
df1.Labels = pd.Categorical(values=df1.Labels, categories=['2', '1', '0'], ordered=True)

sns.set(style='darkgrid', context='notebook')
sns.pairplot(df1, hue='Labels', palette='tab10_r')

df2['Labels'] = df2['Labels'].astype(str)
df2.Labels = pd.Categorical(values=df2.Labels, categories=['0', '1', '2'], ordered=True)
sns.pairplot(df2, hue='Labels', palette='tab10_r')

注:原代码中y_train为笔误,已替换为对应DataFrame的Labels列。

解决方案

传入调色板名称字符串时,seaborn会按照分类列的类别排列顺序,依次从调色板中取色分配,因此类别排序变化时,颜色对应关系会同步改变。
要固定标签和颜色的绑定关系,直接传入**「标签值: 颜色值」格式的字典**作为palette参数即可。该模式下seaborn会严格按照字典的键值匹配颜色,完全不受类别排序影响。

修改步骤:

  1. 定义固定颜色映射字典,色值取自tab10_r调色板,完全匹配需求:
# 固定绑定规则:0=绿色,1=紫色,2=灰色
fixed_palette = {
    '0': '#2ca02c',
    '1': '#9467bd',
    '2': '#7f7f7f'
}
  1. 所有pairplot调用都传入该字典作为palette参数,不管怎么调整分类顺序,颜色对应关系都不会变化:
sns.set(style='darkgrid', context='notebook')
# 绘制类别顺序为['2','1','0']的图表
sns.pairplot(df1, hue='Labels', palette=fixed_palette)
# 绘制类别顺序为['0','1','2']的图表
sns.pairplot(df2, hue='Labels', palette=fixed_palette)

如果后续需要调整颜色,直接修改字典中对应标签的十六进制色值即可,不需要改动其他绘图逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 02:42:28