Draw a trendline with Plotly Line

Viewed 20

Is it possible to draw a trendline with Plotly line graph?

figure = px.line(x=year_week, y=num_accidents,
                 labels=dict(time_from_db="Time", 
                 num_accidents="Num of Accidents"),
                 title="Number of Accidents Per Week", line_shape='spline',
                 trendline="ols")

The above code does not work unless I remove trendline="old".

1 Answers

you can do this using px.scatter instead of px.line;

You just need to update your figure object and change the mode to lines, as:

fig.update_traces(mode = 'lines')

Full code

import pandas as pd
import plotly.express as px

# data
df = px.data.stocks()[['GOOG', 'AAPL']]

# your choices
target = 'GOOG'

# plotly
fig = px.scatter(df, 
                 x=target,
                 y=[c for c in df.columns if c != target],
                 trendline='ols',
                 title="trendline example")
fig.update_traces(mode='lines')
fig.data[-1].line.color='green'
fig

I hope it can solve your problem.

Regards,
Leonardo

Related