如何在同一张seaborn barplot中为不同分组设置不同调色板
Seaborn同图多分组独立调色板实现方案
核心实现代码
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 示例数据 df = pd.DataFrame({'group':['G1','G1','G1','G2','G2','G2','G2','G2','G2','G2','G3','G3'], 'item':['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'k', 'L'], 'result':[1,5,4,10,2,4,13,2,6,11,12,9]}) # 按要求排序:group分组内按result值排序 df.sort_values(by=['group','result'], inplace=True) # 提前获取全量item的顺序,避免绘图时坐标轴分类被截断 all_items = df['item'].tolist() # 配置分组与对应调色板的映射 group_palette_map = { 'G1': 'mako_r', 'G2': 'rocket_r', 'G3': 'crest' } fig, ax = plt.subplots(figsize=(5, 6)) for group_name, pal_name in group_palette_map.items(): group_data = df[df['group'] == group_name] # 生成与当前分组item数量匹配的渐变色列表 group_colors = sns.color_palette(pal_name, n_colors=len(group_data)) # 关键参数order指定全量item顺序,避免seaborn自动重置坐标轴 sns.barplot( y='item', x='result', data=group_data, palette=group_colors, order=all_items, ax=ax, label=group_name ) ax.legend(title='分组') plt.tight_layout() plt.show()
常见问题原因说明
- 直接传递色板名称给
palette参数失效:seaborn柱状图的palette参数默认是为每个hue类别分配单个固定颜色,不支持直接传入色板名生成组内渐变 - 循环绘图仅显示最后一组:未指定
order参数时,seaborn会自动根据当前传入数据的分类值重设坐标轴,其他分组的分类会被直接移除 - 组内颜色顺序/重复异常:调用
sns.color_palette时未指定n_colors,默认仅返回6个颜色,分组item数量超过6时会循环取色导致顺序错乱
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

