esuo2
esuo2

Reputation: 21

Cannot Plot Time alone as x-axis >> TypeError: float() argument must be a string or a number, not 'datetime.time'

I am trying to plot a graph of Time (6:00 am to 6:00 pm) against temperature and other parameters but I have been struggling all week

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import matplotlib.dates as mdates
import datetime
import random
df = pd.read_excel('g.xlsx')
TIME    TEMP    RH  WS  NOISE
0   06:00:00    26.3    78.4    0.1 69.2
1   06:10:00    26.8    77.4    0.0 82.0
2   06:20:00    27.1    76.8    0.2 81.0
3   06:30:00    27.1    76.4    0.3 74.0
4   06:40:00    27.4    75.4    0.4 74.0
... ... ... ... ... ...
68  17:20:00    32.5    57.7    0.5 76.1
69  17:30:00    31.8    60.6    2.2 73.4
70  17:40:00    31.4    60.8    0.4 71.8
71  17:50:00    31.2    61.3    0.2 77.3
72  18:00:00    30.9    62.3    2.2 78.1

even when I try to convert the column to date time

df['TIME'] = pd.to_datetime(df['TIME'],format= '%H:%M:%S' ).dt.time

and I try plotting

plt.plot(df.TIME, df.TEMP)

I get this error message >> TypeError: float() argument must be a string or a number, not 'datetime.time'

please assist me

df.plot works instead of plt.plot

but the downside is I am unable to treat the figure as fig and manipulate the graph

df.plot(x="TIME", y=["TEMP"])
df.plot.line(x="TIME", y=["TEMP"])

enter image description here

The downside with this is the time should start at the beginning 6:00 am and end at 6:00 pm, but it's unable to be manipulated, adding figure doesn't work

fig = plt.figure(1, figsize=(5, 5))

Thanks and waiting for your fast response

Upvotes: 2

Views: 2761

Answers (2)

Owen
Owen

Reputation: 466

I had a similar problem in which the same error message arose, but not using Pandas. My code went something like this:

from datetime import datetime
import matplotlib.pyplot at plt

x = [datetime(2022,1,1, 6).time(),
     datetime(2022,1,1, 9).time(),
     datetime(2022,1,1, 12).time(),
     datetime(2022,1,1, 15).time(),
     datetime(2022,1,1, 18).time()]
y = [1,5,7,5,1]  #(shape of solar intensity)

fig = plt.plot()
ax  = fig.subplot(111)
ax.plot(x,y)            

The problem was that matplotlib could not plot datetime.time objects. I got around the problem by instead plotting y against x1=[1,2,3,4,5] and then setting the x-ticks:

ax.set_xticks(x1, ["6am","9am","12pm","3pm","6pm"]) 

Upvotes: -1

mozway
mozway

Reputation: 260600

You can pass an axes to df.plot:

f, ax = plt.subplots(figsize=(5, 5))
df.plot(x='TIME', y='TEMP', ax=ax)
ax.set_xlim(6*60*60, 18*60*60) # time in seconds

output:

pandas line plot

It looks like scatter plot is not working well with datetime. You can use this workaround:

f, ax = plt.subplots(figsize=(5, 5))
df.plot(x='TIME', y='TEMP', ax=ax, style='.')
ax.set_xlim(6*60*60, 18*60*60)

pandas fake scatter plot

Upvotes: 2

Related Questions