简体   繁体   English

根据X轴上的时间绘制数据

[英]Plot data against time in X axis

I am having a set of python lists and I want to plot a graph with matplotlib in such a way that list of time is plotted in x axis and list of data is plotted in y axis. 我有一组python列表,我想用matplotlib绘制图形,以这样的方式在x轴上绘制时间列表,在y轴上绘制数据列表。

code written by me looks similar to : 我编写的代码类似于:

time =['16:40:48','16:45:48','16:50:48','16:55:48','17:00:48','17:05:48','17:10:48']

data1 = ['702','683','696','666','688','694','699']


fig = plt.figure(figsize=(20.0, 16.0))

ax = fig.add_subplot(1,1,1)

dates = matplotlib.dates.date2num(time)


ax.plot_time(dates,data1)


ax.xaxis.set_major_locator( mdates.MinuteLocator(interval=5) )
ax.xaxis.set_major_formatter( mdates.DateFormatter("%H:%M:%S") )
plt.grid(True)

plt.show()

But this gives me an error saying : 但这给我一个错误,说:

AttributeError: 'str' object has no attribute 'toordinal' AttributeError:'str'对象没有属性'toordinal'

I have looked into somne post regarding the similar issue but couldnt find a desired solution for my problem. 我曾就类似问题调查过严肃的帖子,但找不到适合我问题的解决方案。

From the documentation: 从文档中:

matplotlib.dates.date2num(d):
d is either a datetime instance or a sequence of datetimes.

You'll have to convert your time- strings to datetime objects first. 您必须首先将时间字符串转换为datetime对象。 Anyway, you won't need to convert them to "nums", just plot them and you're fine. 无论如何,您无需将它们转换为“数字”,只需绘制它们就可以了。

For creating datetimes, simply use list comprehension: 要创建日期时间,只需使用列表推导:

datetimes = [datetime.datetime.strptime(t, "%H:%M:%S") for t in time]

and then 接着

ax.plot(datetimes, data1)

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

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