为什么我不能更改 px.scatter 的颜色?

Why I can't change colors of px.scatter?

我合并了px.scatter和px.lines,但是不能改变px.scatter的color_continuous_scale,还有color_continuous_midpoint。有人可以帮帮我吗?

import plotly.graph_objs as go
import plotly.express as px
import pandas as pd

def to_pd(a, b, c):
    p = pd.DataFrame({"Date": a, "Cost": b, 'Color': c})
    return p

fig1 = px.line(x=[1,2,3],y=[10,8,20])

a = [1,2,3,4,5,6]
b = [1,1,1,1,1,1]
c = [1,2,3,5,6,100]
dt = to_pd(a, b, c)
fig2 = px.scatter(dt, x=dt.Date, y=dt.Cost, color=dt.Color, color_continuous_scale='viridis', color_continuous_midpoint=10)

graph = go.Figure(data=fig1.data + fig2.data)
graph.show()

如您所见,中点不等于 10,并且默认设置 color_continuous_scale,而不是 viridis。

  • 您正在丢失 px.scatter 在创建 graph
  • 时创建的 coloraxis
  • 只需 update_layout()coloaxis 配置
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd


def to_pd(a, b, c):
    p = pd.DataFrame({"Date": a, "Cost": b, "Color": c})
    return p


fig1 = px.line(x=[1, 2, 3], y=[10, 8, 20])

a = [1, 2, 3, 4, 5, 6]
b = [1, 1, 1, 1, 1, 1]
c = [1, 2, 3, 5, 6, 100]
dt = to_pd(a, b, c)
fig2 = px.scatter(
    dt,
    x=dt.Date,
    y=dt.Cost,
    color=dt.Color,
    color_continuous_scale="viridis",
    color_continuous_midpoint=10,
)

graph = go.Figure(data=fig1.data + fig2.data).update_layout(
    coloraxis=fig2.layout.coloraxis
)
graph.show()