如何使用matplotlib在python中绘制时间戳? [英] How to plot timestamps in python using matplotlib?
问题描述
我一直在搜索整个谷歌,但看起来我无法找到我正在寻找的东西。
I have been searching about this on entire google, but it looks like I am not able to find exactly what I am looking for.
所以,基本上,我有两个列表:一个列表由时间戳数据组成,第二个列表由与之对应的值组成。
So, basically, I have two lists: one list consists of timestamp data and a second list consists of values that correspond to that.
现在我的问题是:我的时间戳是以下格式
Now my issue is: my timestamps are in a following format
['Mon Sep 1 16:40:20 2015', 'Mon Sep 1 16:45:20 2015',
'Mon Sep 1 16:50:20 2015', 'Mon Sep 1 16:55:20 2015']
所以,在 matplotlib
中使用哪种时间格式?我试图绘制这个直截了当,但它给了我:
So, which time format is used in matplotlib
? I tried to plot this straightaway but it gives me:
ValueError: invalid literal
我可以使用 datetime.datetime.strptime
进行转换吗?如果没有,那么这样做的另一种方式是什么?
Can I use datetime.datetime.strptime
to convert it? If not, then what is the other way of doing it?
以正确的格式转换 timestamp
我应该如何使用相应的值绘制新的转换时间戳?
After converting the timestamp
in the proper format, how should I plot the new converted timestamp with it's corresponding value?
可以使用 matplotlib.pyplot.plot(时间,数据)
或者我必须使用 plot_date
方法绘制吗?
Can I use matplotlib.pyplot.plot(time, data)
or do I have to use plot_date
method to plot it?
推荐答案
Yup,使用strptime
Yup, use strptime
import datetime
import matplotlib.pyplot as plt
x = ['Mon Sep 1 16:40:20 2015', 'Mon Sep 1 16:45:20 2015',
'Mon Sep 1 16:50:20 2015', 'Mon Sep 1 16:55:20 2015']
y = range(4)
x = [datetime.datetime.strptime(elem, '%a %b %d %H:%M:%S %Y') for elem in x]
(fig, ax) = plt.subplots(1, 1)
ax.plot(x, y)
fig.show()
这篇关于如何使用matplotlib在python中绘制时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!