Plotly:如何在短划线中绘制时间序列Plotly

2024-04-30 02:27:00 发布

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

我找了好几天都没找到答案。如何将时间序列数据绘制为具有可选线的折线图

我的数据(熊猫数据框架)描述了不同国家的GDP。索引为国家,列为年份

enter image description here

我找不到将数据传递到划线绘图仪的解决方案。我的x和y值是多少

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

Tags: 数据答案框架时间fig绘制序列国家
1条回答
网友
1楼 · 发布于 2024-04-30 02:27:00

从外观上看,您的示例中的解决方案应该是:

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

绘图1-按数据集中显示的列进行绘图

enter image description here

从这里开始,如果您希望在图例中显示国家,并且在x轴上有时间,您可以将df = df.T添加到混合中,并获得:

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

enter image description here

详细信息

当涉及到绘制time series with plotly.时,有多种可能性。您的示例显示了一个宽格式的数据集。在最新版本中,plotly可以优雅地直接处理long and wide format的两个数据集。如果您需要plotly中的长数据和宽数据的详细信息,还可以仔细查看here

下面的代码段使用了上述方法,但为了让它以完全相同的方式为您工作,您的国家/地区必须设置为dataframe行索引。但是你已经说过了,所以试一下,让我知道它对你的效果如何。还有一件事:通过单击绘图图例中的年份,您可以自由选择要显示的轨迹。下面的代码段生成的图也可以直接在Dash中实现,方法是按照What About Dash?here节下的步骤进行

完整代码:

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

相关问题 更多 >