1

I would like to construct a scatter plot, using date time objects on both axis. Namely, dates (formatted as %YYYY-MM-DD) will be placed on one axis, the second axis will display 24 hour scale (i.e. from 0 to 24) and contain timestamps of events (formatted as %HH:MM in 24-hour format), such a user logging into the server, that occurred on a given date. There could be several events on a particular date, for example, a user logging 2 or 3 times.

My questions: how do I use such datetime objects, while creating a plot using matplotlib? Do I need to convert them in order to feed into matplotlib?

sophros
  • 14,672
  • 11
  • 46
  • 75
user136555
  • 255
  • 2
  • 11
  • If I understand your question correctly, here is a [full demo](https://matplotlib.org/3.1.1/gallery/ticks_and_spines/date_demo_rrule.html#sphx-glr-gallery-ticks-and-spines-date-demo-rrule-py) from the matplotlib docs. – ssp Dec 10 '20 at 07:50
  • 1
    No, you can use the list of `datetime.datetime`s right away – max Dec 10 '20 at 10:09
  • My apologies for not being precise. Being a novice, it is difficult to verbalize the "right" question. I am interested in this part: s = np.random.rand(len(dates)) # make up some random y values -- My "y values" are also datetime objects. Can I plot datetime vs datetime? – user136555 Dec 11 '20 at 03:12

1 Answers1

1

As in https://stackoverflow.com/a/1574146/12540580 :

You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

Plot the dates and values using plot_date:

dates = matplotlib.dates.date2num(list_of_datetimes)
matplotlib.pyplot.plot_date(dates, values)
ArtyGator
  • 61
  • 4
  • 1
    the post that you are referring to is a bit dated. `matplotlib` can handle `datetime`s directly. So there is no need for conversion – max Dec 10 '20 at 10:10
  • Thank you for the answer! To more precise, can I use datetime objects for both x and y axis? i.e. can I have a list of values which also contains datetime objects? – user136555 Dec 11 '20 at 03:10