Plotly线图的趋势线

4

是否有一种简单的方法可以像plotly散点图一样轻松地在plotly express折线图中添加趋势线?

我尝试使用下面的代码行创建我的数据框:

fig = px.line(df4, x=df4["DATE"], y=df4['Ratio'], title="Market Ratio", trendline='ols')

但是它会出现错误。

TypeError: line() got an unexpected keyword argument 'trendline'

感谢您!
1个回答

4
没有,也不需要。你所需要的只有px.scatter以及:
fig.update_traces(mode = 'lines')

如果px.linetrendline属性,那么这将产生与其相同的结果。

enter image description here

完整代码:

# 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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接