首页 > 解决方案 > 如何绘制显示数据变化量的时间序列?

问题描述

例如,我有如下数据:

18:00:00     0
18:00:01    -1
18:00:02    -1
18:00:03    -1
18:00:04     2
18:00:05    -3
18:00:06     1
18:00:07     2
18:00:08     3
18:00:09     4
18:00:10     5
18:00:11     4
18:00:12     3
18:00:13    -1
18:00:14     2
18:00:15     8
18:00:16    11


我想根据以下几点来绘制波浪:

(-1,18:00:03)
(2,18:00:04)
(-3,18:00:05)
(5,18:00:10)
(-1,18:00:13)
(11,18:00:16)

有没有一种简单的方法可以做到这一点?

标签: pythonpandasnumpyplotvisualization

解决方案


我瘦我了解如何选择积分。您可以使用groupby根据系列值符号的变化来创建组。

要区分组,您可以使用Series.shift+ Series.cumsum。我留下了用于形成组的系列结果的细节。

然后我创建了一个函数来根据我认为您想要采用并已应用的标准来获取值groupby.apply

import matplotlib.pyplot as plt
%matplotlib inline
my_serie=pd.Series([0, -1, -1,-1 , 2, -3, 1, 2, 3, 4, 5, 4, 3, -1, 2,8,11],time_serie)

#creating Serie to plot
def get_value(x):
    if len(x)>=3:
        return x.iloc[2]
    elif len(x)>=2:
        return x.iloc[1]
    else:
        return x.iloc[0]
groups=((my_serie.shift()*my_serie)<1).cumsum() 
serie_to_plot=my_serie.groupby(groups).apply(get_value)
#tuple of Serie to plot
s_tuple=(*zip(serie_to_plot,serie_to_plot.index),)
#Show the serie an tuple
print(s_tuple)
print('-'*50)
print(serie_to_plot)

((0, 0), (-1, 1), (2, 2), (-3, 3), (3, 4), (-1, 5), (11, 6))
--------------------------------------------------
0     0
1    -1
2     2
3    -3
4     3
5    -1
6    11
dtype: int64

#Creating figure
plt.figure()
serie_to_plot.plot(figsize=(10,10))
plt.figure()
serie_to_plot.plot(kind='bar',figsize=(10,10))

输出图像:

在此处输入图像描述


在此处输入图像描述

细节

groups

2019-10-18 18:00:00    0
2019-10-18 18:00:01    1
2019-10-18 18:00:02    1
2019-10-18 18:00:03    1
2019-10-18 18:00:04    2
2019-10-18 18:00:05    3
2019-10-18 18:00:06    4
2019-10-18 18:00:07    4
2019-10-18 18:00:08    4
2019-10-18 18:00:09    4
2019-10-18 18:00:10    4
2019-10-18 18:00:11    4
2019-10-18 18:00:12    4
2019-10-18 18:00:13    5
2019-10-18 18:00:14    6
2019-10-18 18:00:15    6
2019-10-18 18:00:16    6
dtype: int64

其他图:

#Creating figure
plt.figure()
serie_to_plot.plot(figsize=(10,10))
serie_to_plot.plot(kind='bar',figsize=(10,10))

在此处输入图像描述


推荐阅读