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

[solved] Unable to add trendlines to subplots following the same code on plotly website

I’m unable to generate the chart “Using update_traces() With Plotly Express Figures” shown on plotly website:

import pandas as pd
import as px

df =

fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", 
                 facet_col="species", trendline="ols", title="Using update_traces() With Plotly Express Figures")

    line=dict(dash="dot", width=4),
    selector=dict(type="scatter", mode="lines"))

I got the following error. May I ask why trendline cannot be added to the three scatter plots here?

ModuleNotFoundError                       Traceback (most recent call last)
      6 fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", 
----> 7                  facet_col="species", trendline="ols", title="Using update_traces() With Plotly Express Figures")
      9 fig.update_traces(

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/plotly/express/ in scatter(data_frame, x, y, color, symbol, size, hover_name, hover_data, custom_data, text, facet_row, facet_col, facet_col_wrap, error_x, error_x_minus, error_y, error_y_minus, animation_frame, animation_group, category_orders, labels, color_discrete_sequence, color_discrete_map, color_continuous_scale, range_color, color_continuous_midpoint, symbol_sequence, symbol_map, opacity, size_max, marginal_x, marginal_y, trendline, trendline_color_override, log_x, log_y, range_x, range_y, render_mode, title, template, width, height)
     53     mark in 2D space.
     54     """
---> 55     return make_figure(args=locals(), constructor=go.Scatter)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/plotly/express/ in make_figure(args, constructor, trace_patch, layout_patch)
   1529             patch, fit_results = make_trace_kwargs(
-> 1530                 args, trace_spec, group, mapping_labels.copy(), sizeref
   1531             )
   1532             trace.update(patch)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/plotly/express/ in make_trace_kwargs(args, trace_spec, trace_data, mapping_labels, sizeref)
    236                     and len(trace_data) > 1
    237                 ):
--> 238                     import statsmodels.api as sm
    240                     # sorting is bad but trace_specs with "trendline" have no other attrs

ModuleNotFoundError: No module named 'statsmodels'

Hi @oat, as the error message says at the end, you have to install statsmodels (pip install statsmodels or conda install statsmodels) since this module is used for computing the trendlines. It is an optional dependency of, we try to keep the list of required dependencies small but it means that sometimes you have to install additional packages.

1 Like

Thanks, @Emmanuelle, your suggestion solved the issue.