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

Plotly Express px.line() color_discrete_map参数失效问题求助

Plotly折线图color_discrete_map颜色映射不生效的解决方案

你遇到的问题核心是color_discrete_map的键与数据中Corporation列的实际值不匹配,导致Plotly无法识别映射关系,从而自动使用默认颜色序列。

排查与解决步骤:

  1. 确认数据中的企业名称
    先打印Corporation列的所有唯一值,检查名称的拼写、大小写、标点是否和你设置的键完全一致:

    print(df["Corporation"].unique())
    

    比如你代码里写的是"Mcdonald's",但数据中实际可能是"McDonald's"(注意字母D的大小写),这类微小差异都会导致映射失效。

  2. 修正color_discrete_map的键
    根据第一步得到的真实名称,调整映射字典的键,确保完全匹配。比如如果数据里是"McDonald's",修正后的映射片段如下:

    color_discrete_map={
        "McDonald's":"#FFFF00",
        "Wendy's": "#DD1438",
        "Burger King": "#F2A900",
        "Taco Bell": "#36399A",
        "KFC": "#f5d4b7"
    },
    
  3. 额外排查点

    • 不要同时使用color_discrete_sequence参数,它会覆盖color_discrete_map的部分设置
    • 若以上步骤无效,可尝试升级Plotly到最新稳定版:pip install --upgrade plotly

修正后的完整代码示例

import pandas as pd
import plotly.express as px

df = pd.read_csv("fastfood.csv")
df.drop(df[df["Year"] < 2018].index, inplace = True)
df["Percent Change"] = df.groupby("Corporation")["Total Revenue"].apply(lambda x: ((x-x.iloc[0]) / x.iloc[0]) * 100)

# 先打印确认企业名称
print(df["Corporation"].unique())

fig = px.line(df,
    x="Date",
    y="Percent Change",
    title="Fast Food Company Revenue Growth",
    render_mode="svg",
    color="Corporation",
    color_discrete_map={
        "McDonald's":"#FFFF00",  # 与数据中实际名称匹配
        "Wendy's": "#DD1438",
        "Burger King": "#F2A900",
        "Taco Bell": "#36399A",
        "KFC": "#f5d4b7"
    },
    width=800,
    height=600,
    )

fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:25:18