How to Fit a Trendline in a Scatter Plot in Plotly(default and your own line)

Renee LIN
2 min readSep 22, 2022

Creating trendlines with Plotly is super easy, but it seems there is no function provided for creating trendlines in multi-plots/subplots. We can just create our own linear regression model to calculate the trendline and plot it.

  1. Plot the trendline using Plotly’s function
  2. Creating our own trendline

1. Plot the trendline using Plotly’s function

This is easy, document link is here

import plotly.express as pxdf = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", facet_col="smoker", color="sex", trendline="ols")
fig.show()
results = px.get_trendline_results(fig)
print(results)
results.query("sex == 'Male' and smoker == 'Yes'").px_fit_results.iloc[0].summary()
Trendline Created
The line in detail

2. Creating our own trendline

from sklearn import preprocessing
from plotly.subplots import make_subplots
fig = make_subplots(rows=2…

--

--

Renee LIN

Passionate about web dev and data analysis. Huge FFXIV fan. Interested in health data now.