Home > Software engineering >  How can I select the temporal resolution of my datetime x-ticks in my matplotlib pyplot plot?
How can I select the temporal resolution of my datetime x-ticks in my matplotlib pyplot plot?

Time:06-23

I am currently plotting a temporal series using pyplot. I have specified the following x-ticks, which consist of four objects of type datetime:

x_ticks
array(['2021-10-17T09:23:11.000000', '2021-10-17T10:02:15.750000',
       '2021-10-17T10:41:20.500000', '2021-10-17T11:20:25.250000'],
      dtype='datetime64[us]')

As you can see, each element (purposely) has a time resolution down to microseconds. So far, so good. However, when I actually get to plot my graph of interest, by default the time axis appears with format YYYY-MM-DD, like in the image below:

enter image description here

It automatically crops the hours and seconds, but I would like to visualize them. How can I specify the resolution of my time x-ticks that needs to appear in the plots?

CodePudding user response:

Use a DateFormatter to set the display of the axis. I also used a LinearLocator to show not all labels, in this case it's 4. And rotated the labels to take up less space with autofmt_xdate().

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates

aaa = np.array(['2021-10-17T09:23:11.000000', '2021-10-17T10:02:15.750000',
       '2021-10-17T10:41:20.500000', '2021-10-17T11:20:25.250000'],
      dtype='datetime64[us]')

bbb = [1, 3, 7, 5]

fig, ax = plt.subplots()
ax.plot(aaa, bbb)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m-%d %H:%M:%S"))
locator = matplotlib.ticker.LinearLocator(4)
ax.xaxis.set_major_locator(locator)
fig.autofmt_xdate()
plt.show()

enter image description here

If subplots with captions are needed, although this was not visible in the question, then the solution is as follows:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import matplotlib.dates

fig, axs = plt.subplots(3, 1, constrained_layout=True, figsize=(7, 7))

aaa = np.array(['2021-10-17T09:23:11.000000', '2021-10-17T10:02:15.750000',
       '2021-10-17T10:41:20.500000', '2021-10-17T11:20:25.250000'],
      dtype='datetime64[us]')
bbb = [1, 3, 7, 5]

lims = aaa[0], aaa[-1]
form = matplotlib.dates.DateFormatter("%Y-%m-%d %H:%M:%S")
locator = matplotlib.ticker.LinearLocator(4)

for nn, ax in enumerate(axs):
    ax.plot(aaa, bbb)
    ax.set_xlim(lims)
    ax.xaxis.set_major_formatter(form)
    ax.xaxis.set_major_locator(locator)
    for label in ax.get_xticklabels():
        label.set_fontsize(7)


plt.show()

enter image description here

  • Related