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

Plotly/Python:px.bar设置color后条形错位、颜色不匹配问题

问题描述

使用Plotly Express的px.bar绘制条形图时,设置color参数后出现两个异常:

  • 条形与X轴标签错位
  • 条形颜色未匹配DataFrame中Color列的自定义颜色值
    未设置color时图表显示正常,相关代码及DataFrame如下:

代码示例

import pandas as pd

df = pd.DataFrame({
    'label': ['Apple', 'Banana', 'Orange', 'Grape', 'Apple', 'Banana', 'Orange', 'Grape', 'Grape'],
    'Count': [1, 2, 2, 2, 3, 5, 6, 3, 3],
    'Color': ['crimson', 'lightslategrey', 'lightslategrey', 'lightslategrey', 'crimson', 'lightslategrey', 'lightslategrey', 'lightslategrey', 'lightslategrey']
})

import plotly.express as px
fig_bar = px.bar(df, x='label', y='Count', color = 'Color',
                 barmode='group')

fig_bar.show()

对应的DataFrame

label   Count   Color
0   Apple   1   crimson
1   Banana  2   lightslategrey
2   Orange  2   lightslategrey
3   Grape   2   lightslategrey
4   Apple   3   crimson
5   Banana  5   lightslategrey
6   Orange  6   lightslategrey
7   Grape   3   lightslategrey
8   Grape   3   lightslategrey

问题原因

  1. 条形错位的原因:Plotly Express的color参数核心作用是做数据分组。当你把Color列传给color参数时,Plotly会将crimson和lightslategrey识别为两个不同的分组类别,再配合barmode='group'的设置,会把同一label下不同分组的条形并排展示。而你的DataFrame中同一label对应多行数据(比如Grape有3行),这就导致每个X轴标签下出现多个分组条形,视觉上呈现出错位效果。

  2. 颜色不匹配的原因:color参数不是用来直接指定颜色值的,它是用来指定分组字段,Plotly会自动为不同分组分配内置的配色方案。你把存储颜色值的Color列传给color,相当于让Plotly按颜色字符串进行分组,而非用这些字符串设置条形颜色,所以自然不会应用你想要的crimson和lightslategrey。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:45:25