如何在python中绘制时间序列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19079143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to plot time series in python
提问by Mohanasundar
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.
我一直在尝试从 CSV 文件绘制时间序列图。我设法读取文件并将数据从字符串转换为日期strptime
并使用列表存储。当我尝试使用包含日期信息的列表在 matplotlib 中绘制测试图时,它将日期绘制为一系列点;也就是说,对于 2012 年 5 月 31 日 19:00 的日期,我在 2012、05、19、31、00 处绘制了一个点,在 y 轴上为 x=1 的值,依此类推。我知道这不是为绘图传递日期信息的正确方法。有人可以告诉我如何正确传递这些信息。
回答by jabaldonedo
Convert your x-axis data from text to datetime.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()