Search code examples
pythonpandasmatplotlibdatetimecolorbar

How to get time from datetime into a string/number for a colormap


I'm trying to shade a scatter plot based on time of day, but my data is in datetime format. Getting either time of day or hours past 00:00 would work. I tried to get just the time from datetime, but I got the following error.

TypeError: float() argument must be a string or a number, not 'datetime.time'

Ideally, I'll have a scatterplot shaded based on time of day.

I initially tried this (also added .values to the end of the dt.time to see if it would help. It didn't).

x = dfbelow[1:].wind_speed.values
y = above_aligned["WS"].values
plt.scatter(x, y, s=20, c=above_aligned["timestamp"].dt.time, cmap='YlOrBr')

plt.xlabel("Below Canopy Wind Speed (m/s)")
plt.ylabel("Above Canopy Wind Speed (m/s)")
plt.title("Above vs. Below Canopy Wind Speeds (m/s)")
plt.colorbar(label="Below Canopy Wind Direction")
plt.show

But it understandably can't shade based off of a datetime form.


Solution

  • I figured it out and it was actually very simple. Instead of above_aligned["timestamp"].dt.time, I just used above_aligned["timestamp"].dt.hour.