How to Fit a Trendline in a Scatter Plot in Plotly(default and your own line)
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.
- Plot the trendline using Plotly’s function
- 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()
2. Creating our own trendline
from sklearn import preprocessing
from plotly.subplots import make_subplotsfig = make_subplots(rows=2…