Custom trendline function in px.Scatter

I would like to be able to show trend lines that are based on weighted least squares regression instead of ordinary least squares regression.

As far as I can tell, it’s only possible to pass string values to the ‘trend_line’ parameter in plotly.express.scatter and these strings are just aliases to functions implemented in px.trendline_functions.

Would it be possible to somehow pass a custom function for the trendline calculation? If not, any idea how I could add custom trendlines to a scatter plot somehow?

HI @tommyteleshop welcome to the forums.

You could calculate the trendline with any python package and add the line/points as trace to the scatterplot.

For example like this (taken from the docs):

import plotly.express as px

df = px.data.iris()

fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
                 title="Using The add_trace() method With A Plotly Express Figure")

fig.add_trace(
    go.Scatter(
        x=[2, 4],
        y=[4, 8],
        mode="lines",
        line=go.scatter.Line(color="gray"),
        showlegend=False)
)
fig.show()