0

Matplotlib has some pretty sophisticated code figuring out how to show labels, but sometimes it cramps its labels more than looks good on presentations. Is there any way to tweek it?

For example, suppose we're plotting something against date:

figure = plt.figure(figsize=(8,1))
ax = plt.gca()
ax.set_xlim(xmin=np.datetime64('2010'), xmax=np.datetime64('2020-04-01'))

We get an x-axis like this:

x axis with tightly packed years

But supposing we want it to show more spaced years, like this:

desired axis

We can kludge it in any given case by editing the labels 'mechanically'. E.g.:

ax.set_xticks([tick for i, tick in enumerate(ax.get_xticks()) if i%2==0]) # Every other year.
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))

But that's fragile, and it breaks whenever the x limits change.

Is there any way to force more spacing in the tick setup algorithm?

CharlesW
  • 955
  • 8
  • 18
  • You can rotate the ticks. But I guess this not the answer you are looking for. Alternatively here is an anwer that might help you. https://stackoverflow.com/questions/44863375/how-to-change-spacing-between-ticks-in-matplotlib – sehan2 Jul 10 '21 at 14:55

1 Answers1

0

Oh! Found the matplotlib source code and it led me to AutoDateLocator:

ax.xaxis.set_major_locator(matplotlib.dates.AutoDateLocator(maxticks=8))

The corresponding locator for non-dates is MaxNLocator .

CharlesW
  • 955
  • 8
  • 18