1

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.

Basically, 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 depending on time, without date information. So, ideally, it should looks like below.

enter image description here

Not like this below.

enter image description here

mocs
  • 101
  • 10

2 Answers2

1

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()
wwnde
  • 26,119
  • 6
  • 18
  • 32
  • You have wrong type. When you have string type values, matplot plots each as a tick . timeseries is notorious for this. Under the hood, matplotlib is set to take properly formatted datetimes. The following post discusses that to some degree https://stackoverflow.com/questions/13515471/matplotlib-how-to-prevent-x-axis-labels-from-overlapping – wwnde Jan 04 '22 at 04:01
  • From @Manlai answer, you can see he has created strings from the datetime and avoided consuming a datetime string. If he has to consume a date time string, it must be an actual properly formatted datetime string. If that helps – wwnde Jan 04 '22 at 04:05
1

This answer is if you're looking to simply change the tick labels. Basically, using set_xticklabels change the xticklabels from the default to hourly:

f, ax = plt.subplots(1,1)
ax.plot(df['date_time'], df['value'],'o--', lw=0)
ax.set_xticks(df['date_time'])
ax.set_xticklabels(df['date_time'].str.split(',').str[1]);

Output:

enter image description here