为折线图绘制趋势线
Plotly Trendline for Line Chart
有什么方法可以轻松地将趋势线添加到 plotly express 折线图中,就像 plotly 散点图一样?
我尝试使用这条线来创建我的数据框:
fig = px.line(df4, x=df4["DATE"], y=df4['Ratio'], title="Market Ratio", trendline='ols')
但是报错
TypeError: line() got an unexpected keyword argument 'trendline'
谢谢!
不,没有。你不需要它。您只需要 px.scatter
和:
fig.update_traces(mode = 'lines')
如果 具有 trendline
属性,这将产生与 px.line
相同的结果。
完整代码:
# 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()
有什么方法可以轻松地将趋势线添加到 plotly express 折线图中,就像 plotly 散点图一样?
我尝试使用这条线来创建我的数据框:
fig = px.line(df4, x=df4["DATE"], y=df4['Ratio'], title="Market Ratio", trendline='ols')
但是报错
TypeError: line() got an unexpected keyword argument 'trendline'
谢谢!
不,没有。你不需要它。您只需要 px.scatter
和:
fig.update_traces(mode = 'lines')
如果 具有 trendline
属性,这将产生与 px.line
相同的结果。
完整代码:
# 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()