Reputation: 449
Is there any way to easily add a trendline to a plotly express line chart like there is for plotly scatter plot?
I have tried using this line to create my dataframe:
fig = px.line(df4, x=df4["DATE"], y=df4['Ratio'], title="Market Ratio", trendline='ols')
But it gives the error
TypeError: line() got an unexpected keyword argument 'trendline'
Thanks!
Upvotes: 4
Views: 5946
Reputation: 61084
No, there isn't. And you don't need it. All you need is px.scatter
and:
fig.update_traces(mode = 'lines')
This will yield the same result as px.line
if it did have a trendline
attribute.
# imports
import pandas as pd
import plotly.express as px
import plotly.io as pio
# data
df = px.data.stocks()[['GOOG', 'AAPL']]
# your choices
target = 'GOOG'
colors = px.colors.qualitative.T10
# plotly
fig = px.scatter(df,
x = target,
y = [c for c in df.columns if c != target],
template = 'plotly_dark',
color_discrete_sequence = colors,
trendline = 'ols',
title = "fig.update_traces(mode = 'lines')")
f = fig.full_figure_for_development(warn=False)
fig.update_traces(mode = 'lines')
fig.data[-1].line.color = 'red'
fig.show()
Upvotes: 4