繁体   English   中英

如何在matplotlib中的一个图上绘制由不同日期但相同时间戳组成的时间序列

[英]How to plot time series that consists of different dates but same timestamps on one graph in matplotlib

我有数据显示在三个不同日期收集的一些值:2015-01-08,2015-01-09和2015-01-12。 对于每个日期,有几个具有时间戳的数据点。

日期/时间在列表中,如下所示:

['2015-01-08-09:00:00', '2015-01-08-10:00:00', '2015-01-08-11:00:00', '2015-01-08-12:00:00', '2015-01-08-13:00:00', '2015-01-09-14:00:00', '2015-01-09-15:00:00', '2015-01-09-16:00:00', '2015-01-12-09:00:00', '2015-01-12-10:00:00', '2015-01-12-11:00:00']

另一方面,我在另一个列表中有相应的值(浮点数):

[12210.0, 12210.0, 12180.0, 12240.0, 12250.0, 12420.0, 12390.0, 12400.0, 12380.0, 12450.0, 12460.0]

为了将所有这些放在一起并绘制图表,我使用以下代码:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as md
import dateutil
from matplotlib.font_manager import FontProperties

timestamps = ['2015-01-08-09:00:00', '2015-01-08-10:00:00', '2015-01-08-11:00:00', '2015-01-08-12:00:00', '2015-01-08-13:00:00', '2015-01-09-14:00:00', '2015-01-09-15:00:00', '2015-01-09-16:00:00', '2015-01-12-09:00:00', '2015-01-12-10:00:00', '2015-01-12-11:00:00']

ticks = [12210.0, 12210.0, 12180.0, 12240.0, 12250.0, 12420.0, 12390.0, 12400.0, 12380.0, 12450.0, 12460.0]

plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation=90 )

dates = [dateutil.parser.parse(s) for s in timestamps]

ax=plt.gca()
ax.set_xticks(dates)
ax.tick_params(axis='x', labelsize=8)

xfmt = md.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)

plt.plot(dates, ticks, label="Price")

plt.xlabel("Date and time", fontsize=12)
plt.ylabel("Price", fontsize=12)
plt.suptitle("Price during last three days", fontsize=12)

plt.legend(loc=0,prop={'size':8})

plt.savefig("figure.pdf")

当我试图绘制这些日期时间和值时,我会得到一个乱七八糟的图形,其中来回的线条。

看起来日期被忽略,只考虑时间戳,这是杂乱图表的原因。 我试图编辑日期时间以具有相同的日期和连续的时间戳,并修复了图表。 但是,我也必须有约会。

我究竟做错了什么?

当我试图绘制这些日期时间和值时,我会得到一个乱七八糟的图形,其中来回的线条。

你的情节遍布整个地方,因为plt.plot按照你给它的顺序连接点。 如果这个顺序在x中没有单调增加,那么它看起来很“混乱”。 您可以先按x对点进行排序以解决此问题。 这是一个最小的例子:

import numpy as np
import pylab as plt

X = np.random.random(20)
Y = 2*X+np.random.random(20)

idx = np.argsort(X)
X2 = X[idx]
Y2 = Y[idx]

fig,ax = plt.subplots(2,1)
ax[0].plot(X,Y)
ax[1].plot(X2,Y2)
plt.show()

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM