Home > Mobile >  Inserting trendline after creating px.scatter (fig)
Inserting trendline after creating px.scatter (fig)

Time:10-14

NAME="Ubuntu" VERSION="20.04.3 LTS (Focal Fossa)"
Streamlit, version 1.12.0
Python 3.8.10
plotly==5.10.0

I have a Streamlit dashboard using plotly express to make the chart. The dashboard allows a user to select different options, and the chart re-creates using those options on the fly.

One of the options is to add a trendline, however I only found way to do this when creating the fig (as an option to the px.scatter() )

Is there a way to add the trendline after the fig = px.scatter has been called?

Current code:

def control_chart_by_compound(
                  df, 
                  x_column_name, 
                  y_column_name, 
                  trendline = False, 
                  trendlinetype = "ols", 
                  trendline_scope="overall", 
                 ):
    
    def _trendlinescatter():
        try: 
            assert trendlinetype == "ols", "Only Ordinary Least Squares (trendlinetype = 'ols') is currently supported."
            fig = px.scatter(x=x_column_name, 
                             y=y_column_name, 
                             labels={
                                 "x": x_column_name,
                                 "y": y_column_name,
                                 color_column_name: "Compounds"
                             },
                             trendline = trendlinetype, 
                             trendline_scope = trendline_scope, 
                            )
            return fig
        
        except Exception as e:
            err = "Unfortunately I'm unable to create a scatter plot with trendline from columns '{}' and '{}'. (ERROR: {})".format(x_column_name, y_column_name, e) 
            print(err)
            return _notrendlinescatter()
            
    def _notrendlinescatter():
        fig = px.scatter(df, 
                         x=x_column_name, 
                         y=y_column_name, 
                         labels={
                             "x": x_column_name,
                             "y": y_column_name,
                             color_column_name: "Compounds"
                         },
                        )
        return fig
                
    if trendline != False: 
        fig = _trendlinescatter()
    else:
        fig = _notrendlinescatter()

CodePudding user response:

I have a workaround to solve this issue which is adding the trendline and then hide it by default and let the user display it. Try to change the value of withTrendline:

import plotly.express as px

withTrendline = False # value comes from the callback 

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")
fig.update_traces(visible=withTrendline, selector=dict(mode="lines")) 
fig.show()
  • Related