-1

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?

jared
  • 4,165
  • 1
  • 8
  • 31
  • Convert the values to a timedelta (with the smallest value being the subtrahend), and then to total_seconds, which will result in an integer. Plot the values against total_seconds, and then reformat the xtick labels with something like https://stackoverflow.com/q/775049/7758804 – Trenton McKinney Aug 15 '23 at 01:02

1 Answers1

0

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

df['Time'] = pd.to_datetime(df['Time'])

misterhuge
  • 354
  • 1
  • 7
  • It did, thank you! Didn't realise Excel would read the time values as a series, until I realised the values had custom formatting in Excel rather than datetime. Importing from a CSV followed by this method made it work. Now just to reformat the xtick labels... – StejnegersScoter Aug 16 '23 at 13:12
  • if you are reading these from a csv check out the date processing with the parse_dates param in pd.read_csv(): https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html – misterhuge Aug 16 '23 at 13:24