[英]plotting dates from time() since the epoch with matplotlib
I'm sourcing date in second since the epoch as a floating point number ( from time.time() ) and I'm trying to plot it converting it like this (line[0]): 我将自纪元起的日期以秒作为浮点数(来自time.time())以秒为单位,并且尝试将其转换为这样的格式(第[0]行):
x,y = [],[]
csv_reader = csv.reader(open(csvFile))
for line in csv_reader:
x.append(float(line[1]))
y.append(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(line[0]))))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y,'o-')
fig.autofmt_xdate()
plt.show()
but matplotlib keeps on erroring out like this : 但是matplotlib继续这样出错:
ValueError: invalid literal for float(): 2013-07-08 15:04:50 ValueError:无效的float()文字:2013-07-08 15:04:50
Any idea on how to format it properly ? 关于如何正确格式化的任何想法吗?
Cheers 干杯
You get a ValueError
since that format is invalid for float()
. 您会收到ValueError
因为该格式对于float()
无效。 Instead of formatting it to a float
value, try appending the formatted string to a list and use the yticks()
function as follows. 与其将其格式化为float
值, yticks()
尝试将格式化的字符串附加到列表中, yticks()
如下所示使用yticks()
函数。
>>> yAxis = ['2013-07-08 15:04:50', '2013-07-08 15:03:50', '2013-07-08 5:04:50']
>>> from random import randint
>>> xAxis = [randint(0, 10) for _ in range(3)]
>>> import pylab as plt
>>> plt.plot(xAxis, range(len(xAxis)))
>>> plt.yticks(range(len(yAxis)), yAxis, size='small')
>>> plt.show()
This gives you a plot like the following, hopefully, that was what you were looking for : 希望您可以看到如下所示的图:
PS - Did you want the dates on the X-Axis? PS-您想要X轴上的日期吗?
Here there is another example, where the spacing between dates are not uniform, and could be randomly distributed: 这是另一个示例,其中日期之间的间隔不均匀,并且可以随机分布:
import numpy as np
import matplotlib.pyplot as plt
import time
time_data = np.array([1373316370.877059,
1373316373.95448,
1373316378.018756,
1373316381.960965,
1373316383.586567,
1373316387.111703,
1373316387.611037,
1373316391.923015,
1373316393.80545,
1373316398.294916])
ydata = np.random.rand(len(time_data))
time_formatted = []
for element in time_data:
time_formatted.append(time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime(element)))
isort = np.argsort(time_data) #Sorting time_data
plt.xticks(time_data[isort],
np.array(time_formatted)[isort],
size='small',
rotation=35)
plt.plot(time_data[isort],ydata[isort],'k-')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.