plotly

Plotly.Express.Get_trendline_results

“In this article, we will explore how to use the get_trendlines_results() function in Plotly express to extract the fit statistics for trendlines. Keep in mind that this function will only extract the fit stats if the figure specified has the trendlines parameter set to “ols”.

Let’s dive in.

Create a Figure With Trendline

The first step is to create a figure with trendlines. For this example, we will use a simple scatter plot using the tips data as shown in the code below:

import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x='total_bill', y='tip', facet_col='smoker', color='sex', trendline='ols')
fig.show()

 
The code above should return a figure as shown:


Once we have the figure with trendlines in the trace, we can extract the underlying model parameters using the get_trendlines_results() function.

The function syntax is as shown:

plotly.express.get_trendline_results(fig)

 
Parameters:

    1. fig – specifies the figure from which we wish to extract the fit statistics. The figure must have the trendline parameter set to ‘ols.

The function will then return a Pandas DataFrame with the px_fit_results columns containing the statsmodels object.

Example

Let us see how we can extract the fit stats using the figure we created earlier. The code is as shown:

result = px.get_trendline_results(fig)
print(result)

 
Output:


We can then access the model parameter as shown in the query below:

import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x='total_bill', y='tip', facet_col='smoker', color='sex', trendline='ols')
result = px.get_trendline_results(fig)
result.query("sex == 'Male' and smoker == 'Yes'").px_fit_results.iloc[0].summary()

 
Result:

Closing

This article covers the basics of using the get_trendline_results function to extract fit statistics for trendlines.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list