将plottime对象用于绘图时的TypeError

时间:2016-11-09 11:27:25

标签: python matplotlib plot

我正在尝试绘制图形,因为我想要x轴的时间和y轴的整数数据。 我收到以下错误

  

TypeError:float()参数必须是字符串或数字

plt.plot(time,data) 在上面的命令中它显示错误 time包含从间隔15:46:00到16:45:00的每一分钟之后的数据点 我还检查了数据类型,它也显示了时间的日期时间。

import matplotlib as plt
import matplotlib
import datetime as db
import matplotlib.pyplot as plt


time=["16:45:00","16:46:00","16:47:00","16:48:00","16:49:00","16:50:00"]
data=[1,2,1,3,4,6]
time1=[]
for tr in time:  
  t=db.datetime.strptime(tr,"%H:%M:%S").time()
  time1.append(t)
plt.plot(time1,data)
plt.show()

1 个答案:

答案 0 :(得分:2)

您需要从.time()

中删除datetime.strptime
time = ["16:45:00", "16:46:00", "16:47:00", "16:48:00", "16:49:00", "16:50:00"]
data = [1, 2, 1, 3, 4, 6]
time1 = []
for tr in time:
    t = db.datetime.strptime(tr, "%H:%M:%S")
    time1.append(t)

fig,ax = plt.subplots()
ax.plot(time1, data)
plt.gcf().autofmt_xdate()  formats the x-axis to get rotate the tick labels 
plt.show()

这产生了数字:

enter image description here

但是,这会在日期时间结束时给你一些额外的零。为了删除它,需要格式化日期时间。这可以通过使用matplotlibs DateFormatter完成。

from matplotlib.dates import DateFormatter

time = ["16:45:00", "16:46:00", "16:47:00", "16:48:00", "16:49:00", "16:50:00"]
data = [1, 2, 1, 3, 4, 6]
time1 = []
for tr in time:
    t = db.datetime.strptime(tr, "%H:%M:%S")
    time1.append(t)

#format the plotting of the datetime to avoid times like 12:45:00.00000000
date_formatter = DateFormatter('%H.%M.%S')

fig,ax = plt.subplots()
ax.plot(time1, data)
ax.xaxis.set_major_formatter(date_formatter)
plt.gcf().autofmt_xdate()
plt.show()

这会产生一个漂亮的外观:

enter image description here