Created a figure but cannot add trendline created with

Hello. I am quite new at Plotly. I have created a Plotly scatterplot using (plotly.graph_objects.figure) but seems I cannot generate trendlines so I have generated a trendline with Plotly express but I cannot put the trendline in the plotly scatterplot. Any help would be appreciated!

Hello @edublan, please post some code so that we can comment on the code your wrote. Can’t you use px.scatter both for plotting the scatter data and the trendline as in ? If you can’t, you can retrieve the trace corresponding to the trendline and add it to another figure as follows

import as px
import plotly.graph_objects as go
tips =
fig = px.scatter(tips, x="total_bill", y="tip", trendline="ols")
trendline =[1] # second trace, first one is scatter
fig2 = go.Figure()

Please also see the doc page for more details about figure, traces, layout and how to create and update these objects. Hope this helps!

1 Like

Thanks. I did not used plotly express for everything as I belive the advenced editing can only be done in plotly…am I right?
Your suggestion seems to work but the regression line is not properly calculated…this is the code I have:

import pandas as pd
import plotly.graph_objects as go
import as px
import numpy as np

df2018 = pd.read_excel (‘Test.xlsx’, sheet_name=‘2018’).iloc[:21]

fig4 = go.Figure()
fig4.add_trace(go.Scatter(x=df2018[‘Ratio of 5/10’], y=df2018[‘10 Year Benefits’],

fig = px.scatter(df2018, x=df2018[‘Ratio of 5/10’].astype(float), y=df2018[‘GHG Benefit Scores’].astype(float), trendline=“ols”)
trendline =[1]


1 Like

You do not use the same data (not the same y) in the two figures so it’s normal that the trendline is not what you would expect. You can use plotly express to generate a figure and then tune the layout and traces using the different update_* methods. In your example, you could call update_layout (etc.) on fig, the figure created by plotly express. Please see for more explanations about creating and updating figures.

1 Like

Sorry that was a mistake from my part. Using now the same variables. Thanks! That works!!

im trying to do as instructed in the link but all i get is a new variable called results that containes: “<statsmodels.regression.linear_model.RegressionResultsWrapper object at 0x000001DC03A79488>”

im using Spyder.

am i missing something?