I’ve been trying hard all day long, but couldn’t figure this one out. Maybe simple, but I can’t get this one. There is a similar question (here), but it does not resolve the issue.
Bascally, I’m trying to plot data with time, but without date information. See my code below, which gives me an error.
import pandas as pd
import matplotlib.pyplot as plt
data = {'date_time': ['2022-01-03, 08:56:23', '2022-01-03, 09:12:39', '2022-01-04, 09:39:49', '2022-01-04, 09:45:19'],
'value': [1200, 150, -300, 450]
}
df = pd.DataFrame(data)
time = pd.to_datetime(df['date_time']).dt.time
value = df['value']
print(time)
plt.plot(time, value,'o--', lw=0);
plt.show()
I’m looking to plot value only depening on time, without date information. So, ideally, it should looks like below.
Not like this below.
Any help would be greatly appreciated. Thank you in advance!
>Solution :
Coerce date_time to datetime and extract the time component using strftime and the plot
df['time']=pd.to_datetime(df['date_time']).dt.strftime('%H:%M:%S')
plt.plot(df['time'], df['value'],'o--', lw=0);
plt.show()
If you wanted rounded up time, see code below.
df['time']=pd.to_datetime(df['date_time']).round('T').dt.strftime('%H:%M:%S')
plt.plot(df['time'], df['value'],'o--', lw=0);
plt.show()


