Plotly:如何在 Dash Plotly 中绘制时间序列

Plotly: How to plot time series in Dash Plotly

我已经搜索了几天,但没有找到答案。如何在 Dash Plotly 中将时间序列数据绘制为具有可选线条的折线图?

我的数据(pandas 数据框)描述了不同国家的 GDP。索引是国家,列是年份。

我找不到将数据传递给 Dash Plotly 线图的解决方案。我的 x 和 y 值是多少?

fig = px.line(df, x=?, y=?)

看起来,您的示例中的解决方案应该是:

fig = px.line(df, x=df.index, y = df.columns)

图 1 - 按列显示在数据集中绘制

从这里开始,如果您想在图例中显示国家并在 x 轴上显示时间,您只需将 df = df.T 添加到组合中并得到:

绘图 2 - 转置数据帧以在 x 轴上显示时间

详情

在绘图方面有多种可能性 time series with plotly. Your example displays a dataset of a wide format. With the latest versions, plotly handles both datasets of long and wide format elegantly straight out of the box. If you need specifics of long and wide data in plotly you can also take a closer look

下面的代码片段使用了上述方法,但为了使它以完全相同的方式为您工作,您的国家/地区必须设置为数据框行索引。但是您已经说过它们是,所以请尝试一下,让我知道它对您有何影响。还有一件事:您可以自由 select 通过单击图例中的年份来显示要显示的痕迹。以下代码片段生成的图形也可以按照 What About Dash? here.

部分下的步骤直接在 Dash 中实现

完整代码:

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio

import plotly.io as pio

# sample dataframe of a wide format
np.random.seed(5); cols = ['Canada', 'France', 'Germany']
X = np.random.randn(6,len(cols))  
df=pd.DataFrame(X, columns=cols)
df.iloc[0]=0;df=df.cumsum()
df['Year'] =  pd.date_range('2020', freq='Y', periods=len(df)).year.astype(str)
df = df.T
df.columns = df.iloc[-1]
df = df.head(-1)
df.index.name = 'Country'

# Want time on the x-axis? ###
# just include:
# df = df.T
##############################

# plotly
fig = px.line(df, x=df.index, y = df.columns)
fig.update_layout(template="plotly_dark")
fig.show()