Plot datetime object as continuous variable

Question:

Need a hand with some plotting on Seaborn (sns). I’m using Python 3.11.4 on Jupyter Notebooks v6.5.4 via the Anaconda Navigator v.23.7.2, on MacOS.

I have a data frame of which a portion is shown below. Behaviour was pre-converted to numeric values using pandas.DataFrame.replace but the issue comes with the Time variable:

data { 'Time' : ['12:27:00', '12:27:00', '12:12:00', '11:55:00', '12:00:00', '12:11:00', '15:28:00','15:20:00','15:40:00','12:10:00']
'Behaviour' : [2,1,1,0,2,0,0,1,1,2]
}
df= pd.DataFrame(data)

When I try to plot this using sns.scatterplot(x="Time",y="Behaviour") the float() argument must be a string or a real number, not 'datetime.time' error message comes up.

However, I don’t want to convert it to a string — I tried that and while I did get a plot, the x-axis labels were all squashed, and I couldn’t change the ticks because Time was now a string. As such, I want to be able to plot Time as a continuous variable. Converting the data frame column to numeric returns all values as NaN.

Is there any way to plot Time as a continuous variable?

Asked By: StejnegersScoter

||

Answers:

Does it work better if you convert ‘Time’ to a datetime?

df[‘Time’] = pd.to_datetime(df[‘Time’])

Answered By: misterhuge
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.