✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚾️ It's finally Baseball season! Root for the home team... & Register for our Sports Analytics Webinar!

Plotly scatterplot trendline appears under the scatter. How do I get the trendline to appear over the scatterplot? [Python]

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

The trendline appears below the scatter, which you can see below:

How do I get the trendline to appear above the scatter?


I think @nicolaskruchten solved this issue here:

fig.data = fig.data[::-1]

I believe what is done here is reordering the figure data from [scatter plot, trendline] so that it goes [trendline, scatterplot] which changes the z-index of the figure.

I would also consider changing the opacity of the scatters as well.

Hopefully that helps.