在 matplotlib 中绘制时间与日期 [英] Plotting Time vs Date in matplotlib

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

问题描述

我有一个 .csv 文件,其中只有两列,日期和时间:

I have a .csv file with only two columns in it, date and time:

    04-02-15,11:15
    04-03-15,09:35
    04-04-15,09:10
    04-05-15,18:05
    04-06-15,10:30
    04-07-15,09:20

我需要使用matplotlib绘制这些数据(最好是在面积图中,还没有到此为止).我需要 y 轴是时间,x 轴是日期.我在时间/日期的某些用法方面遇到了麻烦,希望有人可以看一下我的代码并提供一些指导:

I need this data to be plotted (preferably in an area graph, haven't gotten that far yet) using matplotlib. I need the y-axis to be time, and the x-axis to be date. I'm having trouble wrapping my head around some of the usage for time/date, and was hoping someone could take a look at my code and offer some guidance:

import numpy as np
from pylab import *
import matplotlib.pyplot as plt
import datetime as DT

data= np.loadtxt('daily_count.csv', delimiter=',',
         dtype={'names': ('date', 'time'),'formats': ('S10', 'S10')} )

x = [DT.datetime.strptime(key,"%m-%d-%y") for (key, value) in data ]
y = [DT.datetime.strptime(key,"%h:%m") for (key, value) in data]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid()


fig.autofmt_xdate()
fig.autofmt_ytime()
plt.plot(x,y)
plt.xlabel('Date')
plt.ylabel('Time')
plt.title('Peak Time')
plt.show()

每次尝试运行它时,都会出现此错误:

Each time I try to run it, I get this error:

ValueError: time data '04-02-15' does not match format '%h:%m'

我也怀疑 y 轴的刻度,到目前为止似乎还没有确定.我也非常愿意接受有关此代码其余部分的建议 - 在此先感谢互联网英雄!

I've also got a suspicion about the ticks for the y-axis, which thus far don't seem to be established. I'm very open to suggestions for the rest of this code as well - thanks in advance, internet heroes!

推荐答案

所以回溯告诉你问题所在.它试图将您的日期解析为您的时间,这是您解析这些行中数据的方式的结果:

So the traceback tells you the problem. It is trying to parse your date as your time, and this is a result of the way you parsed the data in these lines:

data= np.loadtxt('daily_count.csv', delimiter=',',
         dtype={'names': ('date', 'time'),'formats': ('S10', 'S10')} )

x = [DT.datetime.strptime(key,"%m-%d-%y") for (key, value) in data ]
y = [DT.datetime.strptime(key,"%h:%m") for (key, value) in data]

有多种解决方案,但'问题的根源;是当您使用loadtxt并定义名称和dtypes时,它会给您返回一个元组列表,即

There are multiple solutions, but the root of the 'problem; is that when you use loadtxt and define the names and dtypes, it gives you back a list of tuples, i.e.,

[('04-02-15', '11:15') ('04-03-15', '09:35') ('04-04-15', '09:10')
('04-05-15', '18:05') ('04-06-15', '10:30') ('04-07-15', '09:20')]

所以当你遍历它时,你实际上是在不断地访问日期:

So when you looped over it, you actually were accessing constantly the dates:

>>> print [key for (key, value) in data]
>>> ['04-02-15', '04-03-15', '04-04-15', '04-05-15', '04-06-15', '04-07-15']

所以您试图将04-02-15"转换为%h:%m"格式,这当然行不通.

So you were trying to turn '04-02-15' into the format '%h:%m', which of course will not work.

要点很明确,您可以使用zip函数取消混淆解析的数据.例如,

To get to the point, you can unconfuse the parsed data using the zip function. For example,

print map(list, zip(*data))
['04-02-15', '04-03-15', '04-04-15', '04-05-15', '04-06-15', '04-07-15']
['11:15', '09:35', '09:10', '18:05', '10:30', '09:20']

此外,您需要检查您传递的日期的格式,例如%h:%m"将不起作用,因为 %h 不存在,而 %m 表示月份.您可以在文档中找到一个很好的摘要,或者在这里:http://strftime.org/.

Also, you need to check the formats for the dates you passed, for example "%h:%m" won't work as %h doesn't exist, and %m means month. You can find a nice summary on the docs, or here: http://strftime.org/.

或者进入正题:

import numpy as np
from pylab import *
import matplotlib.pyplot as plt
import datetime as DT

data= np.loadtxt('daily_count.csv', delimiter=',',
         dtype={'names': ('date', 'time'),'formats': ('S10', 'S10')} )

dates, times = map(list, zip(*data))
print dates, times

x = [DT.datetime.strptime(date,"%m-%d-%y") for date in dates]
y = [DT.datetime.strptime(time,"%H:%M") for time in times]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid()

plt.plot(x,y)
plt.xlabel('Date')
plt.ylabel('Time')
plt.title('Peak Time')
plt.show()

给出以下图:

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

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