How can I change the color of trendline?

fig = px.scatter(trump, x='Population_ln', y='Trump Share', trendline='ols',
                labels={'Population_ln': 'Population (ln)'},
                title='Relationship Between Population and Trump Share',
                template='none')
fig.update_xaxes(showgrid=False)
fig.update_yaxes(showgrid=False)
fig.show()

I have a scatter graph with an OLS trendline, and Iโ€™m trying to just change the color of the trendline to red. How can I do this? I could not find anything in the documentationโ€ฆ

Thank you in advance!

Hi @sarahekim53,

Your fig consists in two traces: one for data points and another for trend line. First inspect which Scatter trace has mode=โ€˜linesโ€™ (although we know that px.line defines it as the second one) :slight_smile:

for d in fig.data:
    print(d['mode'])

Then update the line trace as follows:

fig.data[1].update(line_color='your new color code') 

Thatโ€™s all!

I would recommend the trendline_color_override kwarg in px.scatter as it applies to all facets and traces:

import plotly.express as px

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", facet_col="sex", trendline="ols", trendline_color_override="red")
fig.show()

2 Likes

You can also use the approach in Plotly Express Trendlines, just the Lines to target other properties than the line color. There happens to be a dedicated keyword argument for this one but using .update_traces() you can batch-update any property of any trace matching any selector