【问题标题】:Plot values of two time series with different dates绘制具有不同日期的两个时间序列的值
【发布时间】:2016-07-31 15:01:37
【问题描述】:

我有两个时间序列。每个时间序列(s1 和 s2)由值列表和相应的时间列表(例如时间戳或其他)表示。我正在使用python,所以例如我有:

s1_values = [6,8,6,3,7,9] # len(s1_values) == len(s1_times)
s1_times =  [1,3,6,7,8,12]

s2_values = [3,8,7,2,5,4,6,2] # len(s2_values) == len(s2_times)
s2_times =  [2,4,5,7,8,9,10,13]

我想查看两个时间序列 s1 和 s2 之间的关系,所以我希望能够使用 Matplotlib 绘制 s1_values(在 x 轴上)与 s2_values(在 y 轴上),但由于这两个时间序列没有及时对齐,我不知道该怎么做。

也许对于时间序列有一些常见的方法,但我不知道。

【问题讨论】:

  • 你想把它们画在什么地方?
  • @JamieBull 在 Matplotlib 中。我想要一种聚合时间序列 s,它是 s1 和 s2 的组合。
  • 您是否在同一个图上绘制了 (t1,s1) 和 (t2,s2)?如果没有,那就先做吧。这会让你知道下一步该做什么。
  • @Hun 我做了,但这不是我要求的。
  • 你说的是散点图。但是大小应该匹配。查看我之前提到的图可以为您提供一些线索,您希望如何匹配两个时间序列的大小。

标签: python matplotlib time-series interpolation resampling


【解决方案1】:

您可以使用pandas (docs),它非常适合时间序列数据。在这种情况下,您将创建两个数据框,然后将它们合并和排序。

merge 为您提供了一个合并的“时间”系列(很多关于合并here 的不同方式),将nan 值插入到当时没有值的值列中。然后按共享的Time 列对其进行排序。 df.fillna 函数 (docs) 接受 method 参数,如果它是 ffill 或 pad,则用最后一个有效值填充空白,如果 bfill 用下一个有效值填充。或者,您可以使用 df.interpolate 对缺失值进行线性插值 (docs)。

方便的是pandas 包装matplotlib,因此您可以直接从数据框中进行绘图。

import matplotlib.pyplot as plt
import pandas as pd


s1_values = [6,8,6,3,7,9] 
s1_times =  [1,3,6,7,8,12]

s2_values = [3,8,7,2,5,4,6,2]
s2_times =  [2,4,5,7,8,9,10,13]

df1 = pd.DataFrame(zip(s1_times, s1_values), columns=['Time', 's1 values'])
df2 = pd.DataFrame(zip(s2_times, s2_values), columns=['Time', 's2 values'])

df = df1.merge(df2, how='outer', on='Time', sort='Time')
df.fillna(method='pad', inplace=True)  # or df.interpolate(inplace=True)

df.plot(kind='scatter', x='s1 values', y='s2 values')
plt.show()

使用fillna(method='ffill')

使用interpolate()

【讨论】:

  • 是的,可以。在插入或填充之前,您只需要按时间列排序一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 2017-08-18
  • 1970-01-01
相关资源
最近更新 更多