简体   繁体   English

如何在python中绘制时间序列

[英]How to plot time series in python

I have been trying to plot a time series graph from a CSV file.我一直在尝试从 CSV 文件绘制时间序列图。 I have managed to read the file and converted the data from string to date using strptime and stored in a list.我已经设法读取文件并使用strptime将数据从字符串转换为日期并存储在列表中。 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;当我尝试使用包含日期信息的列表在 matplotlib 中绘制测试图时,它将日期绘制为一系列点; 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.也就是说,对于 2012 年 5 月 31 日 19:00 的日期,我在 2012、05、19、31、00 处绘制了一个点,在 y 轴上为 x=1 的值,依此类推。 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.有人可以告诉我如何正确传递这些信息。

Convert your x-axis data from text todatetime.datetime , use datetime.strptime :将 x 轴数据从文本转换为datetime.datetime ,使用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()

在此处输入图片说明

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

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