折线图的绘制趋势线

2024-04-30 00:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有任何方法可以像绘制散点图那样,轻松地将趋势线添加到绘图仪中

我已尝试使用此行创建数据帧:

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

但它给出了错误

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

谢谢


Tags: 数据方法datetitlelinefig绘制market
1条回答
网友
1楼 · 发布于 2024-04-30 00:41:32

不,没有。你不需要它。您只需要px.scatter和:

fig.update_traces(mode = 'lines')

如果确实具有trendline属性,则这将产生与px.line相同的结果

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

相关问题 更多 >