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

Time:03-24

I am combined px.scatter and px.lines, but can't change the color_continuous_scale of px.scatter, and also color_continuous_midpoint. Could someone help me, please?

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()

As you can see, midpoint doesn't equal 10, and color_continuous_scale is set by default, not the viridis. enter image description here

CodePudding user response:

  • you are loosing the coloraxis that px.scatter has created when creating graph
  • simply update_layout() with the coloaxis configuration
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()

enter image description here

  • Related