Ted
Ted

Reputation: 499

plotting scatter plot with datetime objects with customized

I have the following code

for line in content:

  parse_line = line.split(', ')
  date_and_time = parse_line[0][3:-1]
  kiosk = parse_line[2].replace(" ", "")

  if date_and_time[-1] == ':':
      date_and_time += '0'

  date_obj = datetime.datetime.strptime(date_and_time, '%m/%d/%Y %H:%M:%S')

  if kiosk not in kiosk_dict:
      kiosk_dict[kiosk] = [date_obj]
  else:
      kiosk_dict[kiosk].append(date_obj)


Y = np.ones(len(kiosk_dict['Ortho_2']))
dates = matplotlib.dates.date2num(kiosk_dict['Ortho_2'])

I have a list of datetime objects stored in kiosk_dict['Ortho_2']. How do I draw the scatter plot with x-axis showing %H:%M:%S, ignoring month, day, and year?

Sample Data:

list_dates = ['2018-04-23 00:02:01', '2018-04-23 00:05:03', '2018-04-23 00:08:05', '2018-04-23 00:12:01']

Upvotes: 0

Views: 809

Answers (1)

harpan
harpan

Reputation: 8631

You need:

import matplotlib.dates as mdates
list_dates = ['2018-04-23 00:02:01', '2018-04-23 00:05:03', '2018-04-23 00:08:05', '2018-04-23 00:12:01']
df = pd.DataFrame({
    'date':list_dates,
    'col':[10,20,30,40]
})
df['date'] = pd.to_datetime(df['date'])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot_date(df['date'], df['col'])
myFmt = mdates.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_formatter(myFmt)

Output:

enter image description here

Upvotes: 1

Related Questions