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?

3
  • If I understand your question correctly, here is a full demo from the matplotlib docs. Commented Dec 10, 2020 at 7:50
  • 1
    No, you can use the list of datetime.datetimes right away Commented Dec 10, 2020 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? Commented Dec 11, 2020 at 3:12

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

the post that you are referring to is a bit dated. matplotlib can handle datetimes directly. So there is no need for conversion
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.