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

Plotly Express修改折线图线条颜色时遇到报错该如何解决

问题原因

你之前两种写法报错,以及color_discrete_map不生效的原因如下:

  • update_layout 用于修改画布布局(标题、坐标轴、图例等全局属性),而折线的颜色、宽度属于数据轨迹(trace)的属性,不能在布局参数中定义,所以会报属性不存在的错误
  • color_discrete_map 需要和px.line的color参数配套使用,你没有指定color参数的情况下,这个映射配置不会生效
解决方案

方法1:使用update_traces修改(最通用,推荐)

直接调用fig的update_traces方法修改轨迹属性,单条折线直接传入样式参数即可:

fig = px.line(data, x="DateTime", y="Gold", title="Gold Prices")
# 自定义折线样式
fig.update_traces(
    line=dict(
        color="#00ff00", # 可传十六进制、rgb、颜色名等格式
        width=5,
        # 可选配置,比如虚线样式:dash='dash'
    )
)
fig.show()

如果是多条折线,可通过selector参数指定修改某一条:

# 例如同时绘制黄金、白银两条折线
fig = px.line(data, x="DateTime", y=["Gold", "Silver"], title="Metal Prices")
# 仅修改黄金折线的样式
fig.update_traces(
    line=dict(color="gold", width=5),
    selector=dict(name="Gold")
)
# 修改所有折线的宽度
fig.update_traces(line=dict(width=3))

方法2:在px.line中直接配置颜色

如果要使用color_discrete_map,需要补充color参数,参数值和你y轴的列名保持一致即可:

fig = px.line(data, x="DateTime", y="Gold", title="Gold Prices", 
              template="ggplot2",
              color="Gold", # 新增该参数,和y列名对应
              color_discrete_map={"Gold": "green"})

如果是多条折线,直接给每个列名配置对应的颜色即可:

fig = px.line(data, x="DateTime", y=["Gold", "Silver"], title="Metal Prices",
              color_discrete_map={"Gold": "gold", "Silver": "silver"})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:39:03