如何绘制时间序列图。

16

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

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>

一个新的图形窗口被打开,但是它显示图1(未响应)

所以,我有两个问题:

  1. 在上面的图中,我们可以看到x轴有索引,但我想让它成为那里的Datum值。如何更改?
  2. 我想在seaborn或plotly中实现这一点,是否有办法在其中实现所有这些?

嗯,按照你的方式并使用典型的sns.lineplot(x='Datum', y='Menge', data=data)对我有效。这些列的数据类型是什么? - m13op22
@HS-nebula 输出[3]: 日期 对象 数量 浮点数 dtype: 对象 - some_programmer
你是如何运行你的代码的? - m13op22
还可以尝试使用 cufflinks 与 plotly 一起使用。 - Ben
4个回答

18

即使是多个时间序列,最干净的设置如下:

  • plotly:px.line()

  • seaborn:lineplot()


plotly:

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

enter image description here


Seaborn:

sns.lineplot(data = df)

Seaborn和Plotly的完整代码:

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

enter image description here


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)

13

考虑一个玩具数据框:

  • Seaborn解决方案
import pandas as pd
import matplotlib.pyplot as plt

import seaborn as sns

df = pd.DataFrame({"Datum": ['1/1/2018 0:00',
                             '1/1/2018 0:15',
                             '1/1/2018 0:30',
                             '1/1/2018 0:45',
                             '1/1/2018 1:00',
                             '1/1/2018 1:15',
                             '1/1/2018 1:30',
                             '1/1/2018 1:45 '],
                   "Menge": [19.5, 19.,19.5,19.5,21,19.5,20,23]})
sns.lineplot(x="Datum", y="Menge", data=df)
plt.xticks(rotation=15)
plt.title('seaborn-matplotlib example')
plt.show()

enter image description here

  • Plotly 解决方案
import pandas as pd
import numpy as np

import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)

trace1 = go.Scatter(x=df.Datum,
                    y=df.Menge,
                    name = "plotly example",
                    line = dict(color = 'blue'),
                    opacity = 0.4)

layout = dict(title='plotly example',)

fig = dict(data=[trace1], layout=layout)
iplot(fig)

enter image description here


嗨,我尝试了你用Plotly提出的建议,它没有错误运行,但在spyder中没有输出图形,但在Jupyter中有输出。有什么想法为什么会这样? - some_programmer
1
你可以将代码的最后一行修改为 plot(fig),然后你就可以得到一个 HTML 页面。 - sentence

2
现在在Plotly中,这比以前容易多了。
# IMPORTS
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px

# EXTRACT THE DATA
df = pd.DataFrame(
    {
        "Datum": [
            "1/1/2018 0:00",
            "1/1/2018 0:15",
            "1/1/2018 0:30",
            "1/1/2018 0:45",
            "1/1/2018 1:00",
            "1/1/2018 1:15",
            "1/1/2018 1:30",
            "1/1/2018 1:45 ",
        ],
        "Menge": [19.5, 19.0, 19.5, 19.5, 21, 19.5, 20, 23],
    }
)

Plotly

px.line(x="Datum", y="Menge", data_frame=df, title="plotly example")

enter image description here

Seaborn/Matplotlib

(代码与顶部答案中的代码相同)

sns.lineplot(x="Datum", y="Menge", data=df)
plt.xticks(rotation=15)
plt.title('seaborn-matplotlib example')

enter image description here


0
这里提供的Plotly解决方案非常棒。使用figure对象,为我的数据设置标签字典也很容易 - 因为政府给出的数据名称几乎没有描述性。所以仅需几行代码:
columns = ['CPALTT01USM657N', 'UNRATE', 'TB3MS']
names = {'CPALTT01USM657N': 'Inflation Rate',
         'UNRATE': 'Unemployment Rate', 
         'TB3MS': '3 Mo. T-Bill Rate'}

fig = go.Figure([{
    'x': monthly_data['DATE'],
    'y': monthly_data[col],
    'name': names[col]
}  for col in columns])
fig.show(renderer='iframe')

生成了以下的Plotly图表: 输入图像描述

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接