python - Plotly Trendline for Line Chart
问题描述
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!
解决方案
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.
Complete code:
# 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()
推荐阅读
- ios - 如何删除应用程序沙箱中的文件?
- android - 如何在 CollapsingLayout 下的 CoordinatorLayout 中正确对齐元素?
- node.js - NGINX 在 COPY 失败 --from=node /app/dist/comp-lib /usr/share/nginx/html,
- r - R - 在数据框的两列中删除相同的名称
- c# - 在表 B 中创建行时如何更新表 A 中的值?
- javascript - 角度组件中的@Input() 属性返回空数组
- python - Databricks 未在 SQL 查询中更新
- php - 如何使用 PHP 和 Mysqli 将 db 结果显示为 HTML 下拉列表中的选项?
- domain-driven-design - 多个聚合根之间的关系
- python-3.x - 矩形中的点 全部