I'm trying to plot a trendline for a Plotly scatterplot and I can't figure out how to get the trendline to appear over the scatter. Below is the code that I used:
import plotly.express as px
fig = px.scatter(df, x='Percentage_LIFT', y='Average_Daily_Contacts',
title='Percent on LIFT vs Average Daily Contacts',
trendline = "ols", trendline_color_override="red")
fig.show()
Here is the scatterplot the code produced:

How do I get the trendline to appear over the scatter?
I'm not seeing the same behavior on my end using px.scatter. But as long as you only have one trace showing the scatter points, and one trace showing the trend line, you can just use the following to switch the order your data appears in your figure object with:
fig.data = fig.data[::-1]
This will turn this:

Into this:

# imports
import pandas as pd
import plotly.express as px
# data
df = px.data.stocks()[['GOOG', 'AAPL']]
# your choices
target = 'GOOG'
# plotly
fig = px.scatter(df,
x = target,
y = [c for c in df.columns if c != target],
template = 'plotly_dark',
trendline = 'ols',
title = "fig.update_traces(mode = 'lines')",
trendline_color_override='red')
fig.data = fig.data[::-1]
fig.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With