如何在python中绘制时间序列 [英] How to plot time series in python

查看:195
本文介绍了如何在python中绘制时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从CSV文件绘制时间序列图.我已经设法读取文件,并使用strptime将数据从字符串转换为日期,并存储在列表中.当我尝试在matplotlib中绘制一个包含日期信息的列表的测试图时,它将日期绘制为一系列点.也就是说,对于日期为2012年5月31日19:00的时间,我在y轴上得到一个在2012、05、19、31、00点带有点的图,其中x = 1的值依此类推.我知道这不是传递日期信息进行绘图的正确方法.有人可以告诉我如何正确传递此信息.

I have been trying to plot a time series graph from a CSV file. I have managed to read the file and converted the data from string to date using strptime and stored in a list. When I tried plotting a test plot in matplotlib with the list containing the date information it plotted the date as a series of dots; that is, for a date 2012-may-31 19:00 hours, I got a plot with a dot at 2012, 05, 19, 31, 00 on y axis for the value of x=1 and so on. I understand that this is not the correct way of passing date information for plotting. Can someone tell me how to pass this information correctly.

推荐答案

将x轴数据从文本转换为 datetime.strptime :

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

这是一个在具有日期时间数组时如何绘制数据的示例:

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

这篇关于如何在python中绘制时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆