Plotly Express Line Chart Color

I am creating a simple line chart with plotly express. There are 3 lines and I would like to assign custom colors to each line. Is this possible?

Something like:

fig = px.line(df, 'x', 'y')
fig.update_traces(line_color='#456987')

fig2 = px.line(df, 'xx', 'yy')
fig2.update_traces(line_color='#147852')

from what I understood, you can use all the plotly properties with plotly.express by passing the arguments in the update_traces method.

Cheers

Matteo

Can someone extend this answer and cater for the case of multiple lines in the same plot? For example, say the figure is created by:

fig = px.line(df, x="Date", y=["Averaged", "Raw"])

How can I control the colors assigned to the lines? I tried fig.update_traces(line_color=["#456987", "#147852"]) but it didn’t work… Any idea?

This worked well for me:

fig = px.line(df, x=“day”, y=“count”, color=‘year’, color_discrete_sequence=[‘gray’, ‘blue’])

You can add a color list using the color_discrete_sequence.

2 Likes

@drorata try this:

import plotly.express as px
import pandas as pd

df = pd.DataFrame(dict(
    Date=[1,2,3],
    Averaged=[1,2,3],
    Raw=[2,3,1]
))
fig = px.line(df, x="Date", y=["Averaged", "Raw"],
             color_discrete_map={
                 "Average": "#456987",
                 "Raw": "#147852"
             })

fig.show()
1 Like

@nicolaskruchten That’s the right direction I believe, but I’m afraid it is not doing what I’m expecting. For example, the following:

fig = px.line(df, x="Date", y=["Averaged", "Raw"],
             color_discrete_map={
                 "Average": "blue",
                 "Raw": "goldenrod"
             })
fig.show()

yields something like:

As you can see, the color of “Averaged” is not really blue… What’s the solution?

The values must match exactly so you need the “d” in “Averaged” :slight_smile:

(The error comes from my code, clearly, so the fault is mine!)