Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading