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, cols=2,subplot_titles=("rmse_v","rmse_v_dif","rmse_s","rmse_a",))
...
...fig.add_trace(go.Scatter(x=X, y=y, mode=’markers’)) #scatter
model = LinearRegression().fit(X,y)
y_hat = model.predict(X)
fig.add_trace(go.Scatter(x=X, y=y_hat, mode='lines')) #Trendline
...
...
That’s it. Here are other visuals created by Plotly.
- Multi-dimensional Data Visualization with Plotly (3D-7D)
- How to Create Heatmap with Plotly for Data Analysis
Medium is an open platform where readers find dynamic thinking, and where expert and undiscovered voices can share their writing on any topic. Subscribe to unlock more articles at Medium.





