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 https://plot.ly/python/linear-fits/#linear-fit-trendlines-with-plotly-express ? If you can’t, you can retrieve the trace corresponding to the trendline and add it to another figure as follows
import plotly.express as px import plotly.graph_objects as go tips = px.data.tips() fig = px.scatter(tips, x="total_bill", y="tip", trendline="ols") trendline = fig.data # second trace, first one is scatter fig2 = go.Figure() fig2.add_trace(trendline) fig2.show()
Please also see the doc page https://plot.ly/python/creating-and-updating-figures/ for more details about figure, traces, layout and how to create and update these objects. Hope this helps!
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 plotly.express 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 = fig.data
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 https://plot.ly/python/creating-and-updating-figures/#updating-figures for more explanations about creating and updating figures.
Sorry that was a mistake from my part. Using now the same variables. Thanks! That works!!
im trying to do as instructed in the https://plot.ly/python/linear-fits/#linear-fit-trendlines-with-plotly-express 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?