0

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']
Ted
  • 469
  • 4
  • 16
  • Refer to: https://stackoverflow.com/questions/14946371/editing-the-date-formatting-of-x-axis-tick-labels-in-matplotlib – harvpan Jun 04 '18 at 20:52
  • But that is not my main question – Ted Jun 04 '18 at 20:54
  • all you got to use is use [DateFormatter](https://matplotlib.org/examples/api/date_demo.html). If you can post your input data, may be I can help you. – harvpan Jun 04 '18 at 20:56
  • The input is read from the file, but I just added some example data. Thanks. – Ted Jun 04 '18 at 21:02

1 Answers1

1

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

harvpan
  • 8,571
  • 2
  • 18
  • 36