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

Plotly柱状图自定义RGB颜色不生效问题求助

解决Plotly柱状图颜色渲染错误及图例显示异常问题

问题根源

你当前代码中color=incidents_by_state.index.map(color_dict)这一行,直接将RGB字符串作为分类值传给了color参数,导致Plotly把这些RGB字符串当成了图例标签,而非以州名作为分类维度来匹配颜色。

修正方案

将color参数指定为州名(即数据的索引),同时保留color_discrete_map=color_dict来关联州名与对应的RGB颜色,这样既能复用全局的color_dict,又能正确渲染颜色和显示州名图例。

修正后的完整代码

import pandas as pd
import plotly.express as px

# 注:原代码中df_main未定义,此处假设数据源为df,实际使用时可替换回正确的数据源
df = pd.DataFrame({
    'state': ['TX', 'TX', 'CA', 'WI', 'TX'],
    'incident_type': ['Fire', 'Fire', 'Storm', 'Snow', 'Fire']
})

color_dict = {}
for i, state in enumerate(df['state'].unique()):
  color = 'rgb(' + ','.join(map(str, [((i + 5) * 71) % 255, ((i + 5) * 83) % 255, ((i + 5) * 97) % 255])) + ')'
  color_dict[state] = color

def incident_by_state(filter):
  incidents_by_state = (
      filter.groupby(by=["state"]).count()[["incident_type"]].sort_values(by="incident_type") 
  )

  fig_incidents_by_state = px.bar(
    incidents_by_state,
    y=incidents_by_state.index,
    x="incident_type",
    labels={"incident_type": "No. Incidents", "state": "State"},
    color=incidents_by_state.index,  # 改为州名作为分类依据
    color_discrete_map=color_dict,   # 保留全局颜色映射表
    title="Total Incidents in each State")

  fig_incidents_by_state.update_layout(
      yaxis=dict(autorange="reversed")
  )
  return fig_incidents_by_state

# 测试调用示例
fig = incident_by_state(df)
fig.show()

关键逻辑说明

  • color参数用于指定图表的分类维度(此处为州名),Plotly会自动以此生成对应的图例标签
  • color_discrete_map负责将每个分类值(州名)映射到你预先定义的RGB颜色,完美复用全局的color_dict

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:07:14