如何在Python中绘制两个不同时间间隔的时间序列在同一张图上

8

我有两个不同的时间序列,想在同一张图上绘制它们。

它们都是在12:30:00~1:25:00之间的序列,但它们的时间序列不同:一个是5秒,另一个约为10.3秒。两个序列的类型均为“pandas.core.series.Series”。时间索引的类型为字符串,由strftime生成。 例如, A序列将是:

12:30:05    0.176786
12:30:15    0.176786
12:30:26    0.176786
...
13:22:26    0.002395
13:22:37    0.002395
13:22:47    0.001574

而B系列将是:
12:30:05    0.140277
12:30:10    0.140277
12:30:15    0.140277
...
13:24:20    0.000642
13:24:25    0.000642
13:24:30    0.000454

我尝试将这两个系列绘制在同一个图表上:

import matplotlib.pyplot as plt
A.plot()
B.plot()
plt.gcf().autofmt_xdate()
plt.show()

而它的工作原理如下:

enter image description here

在第一个图中,蓝色线条在大约12:55:05消失是显而易见的,这是因为A系列只有B系列一半的x点,并且plot()函数仅根据x轴的顺序排列图形,而不是时间间隔。
如果我只绘制A系列,那就很清楚了。

enter image description here

我希望将两个系列显示在同一图中,并按照真实时间间隔进行排列。理想情况下,图应该类似于:

enter image description here

我希望我已经表达清楚了。如果有任何困惑,请告诉我。

你的代码中的 ax 是什么?你是如何存储这两个序列的?你能将其转换为 MCVE 吗? - tmdavison
对于我的错误表示抱歉,我已经进行了更正。在原帖中,a代表A系列,x代表B系列。我不知道将数据在线上验证的好方法是什么。也许只使用我发布的数据(每个系列6个数据点)就可以了。 - user3284048
1
AB的类型是什么?是Pandas数据框吗?如果是,您应该提到它... - Bas Swinckels
1
将您的x值(无论是什么)转换为时间戳,并明确地根据时间绘制。例如,http://stackoverflow.com/questions/24223378/autoscaling-in-matplotlib-plotting-different-time-series-in-same-chart?rq=1 - cphlewis
1个回答

8

这是直接创建日期时间,而不是将它们转换为字符串;根据您的原始格式,您可能希望改用 matplotlib.dates.datestr2num。然后它们将被转换为Matplotlib的日期时间表示形式。虽然这似乎很麻烦,但这意味着时间间隔将正确。

import matplotlib.pyplot as plt
from matplotlib.dates import date2num , DateFormatter
import datetime as dt

 # different times from the same timespan
TA = map(lambda x: date2num(dt.datetime(2015, 6, 15, 12, 1, x)),
         range(1, 20, 5))
TB = map(lambda x: date2num(dt.datetime(2015, 6, 15, 12, 1, x)),
         range(1, 20, 3))
A = [1.2, 1.1, 0.8, 0.66]
B = [1.3, 1.2, 0.7, 0.5, 0.45, 0.4, 0.3]

fig, ax = plt.subplots()
ax.plot_date(TA, A, 'b--')
ax.plot_date(TB, B, 'g:')
ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))
plt.show()

enter image description here


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