gpt4 book ai didi

python - 如何使用 seaborn 或 plotly 绘制时间序列图?

转载 作者:太空宇宙 更新时间:2023-11-03 13:55:40 25 4
gpt4 key购买 nike

我有一个时间序列数据如下:

Datum   Menge
1/1/2018 0:00 19.5
1/1/2018 0:15 19.0
1/1/2018 0:30 19.5
1/1/2018 0:45 19.5
1/1/2018 1:00 21.0
1/1/2018 1:15 19.5
1/1/2018 1:30 20.0
1/1/2018 1:45 23.0

数据框 data 的形状为 (14880, 2)。在Menge列中,只有11807个值可用,其余为nan

我正在尝试按如下方式绘制它:

data.plot()
plt.show()

这给了我

Graph

但我想使用 seabornplotly 绘制相同的图

对于 seaborn 我试过:

x = data.Datum
y = data.Menge.values
sns.lineplot(x = x, y = y, data = data)

它给我的输出是:

Out[3]: <matplotlib.axes._subplots.AxesSubplot at 0x21286bb8668>

并打开了一个新的图形窗口,但显示的是 Figure 1 (Not Responding)

所以,我有两个问题:

  1. 在上图中,我们可以看到 x 轴有索引,但我希望它是那里的 Datum 值。如何改变?
  2. 我想在 seaborn 或 plotly 中实现这一目标,那么有没有办法在这两者中实现这一切?

最佳答案

即使对于多个时间序列,最简洁的设置是:

  • 绘图:px.line()

  • seaborn:lineplot()


plotly :

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

enter image description here


Seaborn:

sns.lineplot(data = df)

enter image description here


seaborn 和 plotly 的完整代码:

以下代码示例可让您生成这两个图。

import plotly.graph_objs as go
from datetime import datetime
import plotly.express as px
import matplotlib as mpl
import seaborn as sns
import pandas as pd
import numpy as np


# sample data in a pandas dataframe

np.random.seed(23)
observations = 75
df=pd.DataFrame(dict(A=np.random.uniform(low=-1, high=1.1, size=observations).tolist(),
B=np.random.uniform(low=-1, high=1.1, size=observations).tolist(),
C=np.random.uniform(low=-1, high=1.1, size=observations).tolist(),
))
df.iloc[0,] = 0
df = df.cumsum()

firstdate = datetime(2020,1,1)
df['date'] = pd.date_range(firstdate, periods=df.shape[0]).tolist()
df.set_index('date', inplace=True)

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



# fig = go.Figure([{
# 'x': df.index,
# 'y': df[col],
# 'name': col
# } for col in df.columns])
# fig.show()

# sns.set_style("darkgrid")
#sns.lineplot(data = df)

plotly express

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

另一个 plotly 选项是:

plotly graph_objects

fig = go.Figure([{
'x': df.index,
'y': df[col],
'name': col
} for col in df.columns])
fig.show()

seaborn

sns.set_style("darkgrid")
sns.lineplot(data = df)

关于python - 如何使用 seaborn 或 plotly 绘制时间序列图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56150437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com