Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas time plot without date

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

Not like this below.

enter image description here

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()

enter image description here

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading