3

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?

vestland
  • 55,229
  • 37
  • 187
  • 305
noha54
  • 33
  • 1
  • 1
  • 5
  • How did my suggestion work out for you? – vestland Apr 10 '21 at 22:43
  • Unfortunately, it didn't change the graph. I appreciate the suggestion though! I ended up using seaborn for the plot instead. – noha54 Apr 12 '21 at 01:55
  • If that didn't change the graph then you would have to share a sample of your data in order to make your provided snippet reproducible. If you feel you're done with the issue, would you consider marking my suggestion as the accepted answer? – vestland Apr 12 '21 at 06:41

1 Answers1

2

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()
vestland
  • 55,229
  • 37
  • 187
  • 305