Black Lives Matter. Please consider donating to Black Girls Code today.

Linear and Non-Linear Trendlines in Python

Add linear Ordinary Least Squares (OLS) regression trendlines or non-linear Locally Weighted Scatterplot Smoothing (LOEWSS) trendlines to scatterplots in Python.

If you're using Dash Enterprise's Data Science Workspaces, you can copy/paste any of these cells into a Workspace Jupyter notebook.
Alternatively, download this entire tutorial as a Jupyter notebook and import it into your Workspace.
Find out if your company is using Dash Enterprise.

Install Dash Enterprise on Azure | Install Dash Enterprise on AWS

New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Linear fit trendlines with Plotly Express

Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on a variety of types of data and produces easy-to-style figures.

Plotly Express allows you to add Ordinary Least Squares regression trendline to scatterplots with the trendline argument. In order to do so, you will need to install statsmodels and its dependencies. Hovering over the trendline will show the equation of the line and its R-squared value.

In [1]:
import as px

df =
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")

Fitting multiple lines and retrieving the model parameters

Plotly Express will fit a trendline per trace, and allows you to access the underlying model parameters for all the models.

In [2]:
import as px

df =
fig = px.scatter(df, x="total_bill", y="tip", facet_col="smoker", color="sex", trendline="ols")

results = px.get_trendline_results(fig)

results.query("sex == 'Male' and smoker == 'Yes'").px_fit_results.iloc[0].summary()
      sex smoker                                     px_fit_results
0  Female     No  <statsmodels.regression.linear_model.Regressio...
1  Female    Yes  <statsmodels.regression.linear_model.Regressio...
2    Male     No  <statsmodels.regression.linear_model.Regressio...
3    Male    Yes  <statsmodels.regression.linear_model.Regressio...
OLS Regression Results
Dep. Variable: y R-squared: 0.232
Model: OLS Adj. R-squared: 0.219
Method: Least Squares F-statistic: 17.56
Date: Tue, 12 Jan 2021 Prob (F-statistic): 9.61e-05
Time: 18:45:57 Log-Likelihood: -101.03
No. Observations: 60 AIC: 206.1
Df Residuals: 58 BIC: 210.2
Df Model: 1
Covariance Type: nonrobust
coef std err t P>|t| [0.025 0.975]
const 1.4253 0.424 3.361 0.001 0.576 2.274
x1 0.0730 0.017 4.190 0.000 0.038 0.108
Omnibus: 21.841 Durbin-Watson: 1.383
Prob(Omnibus): 0.000 Jarque-Bera (JB): 33.031
Skew: 1.315 Prob(JB): 6.72e-08
Kurtosis: 5.510 Cond. No. 60.4

[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

Non-Linear Trendlines

Plotly Express also supports non-linear LOWESS trendlines.

In [3]:
import as px

df ="year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent", trendline="lowess")

What About Dash?

Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash at

Everywhere in this page that you see, you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:

import plotly.graph_objects as go # or as px
fig = go.Figure() # or any Plotly Express function e.g.
# fig.add_trace( ... )
# fig.update_layout( ... )

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div([

app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter