Rajat Singh
Rajat Singh

Reputation: 93

TypeError when using datetime objects for plots

I am trying to plot the graph as I want time in x axis and integer data in y axis. I am getting the following error

TypeError: float() argument must be a string or a number

plt.plot(time,data) on the above command it is showing the error time contains the data points from after every one minute of interval 15:46:00 to 16:45:00 i have also checked the data type also it is showing datetime for time .

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()

Upvotes: 1

Views: 735

Answers (1)

DavidG
DavidG

Reputation: 25380

You need to remove the .time() from your 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()

This produces the figure:

enter image description here

However, this gives you some extra zeros at the end of the datetimes. In order to remove this then the datetimes need to be formatted. This can be done by using 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()

This produces a nice looking figure:

enter image description here

Upvotes: 2

Related Questions