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

Viewed 387

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:

enter image description here

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

1 Answers

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:

enter image description here

Into this:

enter image description here

Complete code:

# 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()
Related