I am drawing matplotlib plots and my x axis consists of YYYYMM formatted strings of year and month like 201901
for January of 2019.
My problem is that some of the data spans on a long period of time and this makes the x axis tick labels so dense that they pile up on each other and they become unreadable.
I tried making the font smaller and I rotated the labels 90 degrees which helped a lot but it is still not enough for some of my data.
Here is an example of one of my x axis which looks ok:
And here is an example of an x axis which is too dense because the data spans on a long period of time:
So I want matplotlib to skip printing a few tick labels when the tick labels start piling up on each other. For example, print the label for January, skip printing the labels for February, March, April and May, print the label for June, and skip printing the labels for July, August etc. But I don't know how to do this?
Or are there any other kind of solutions I can use to overcome this problem?
A quick dirty solution would be the following:
ax.set_xticks(ax.get_xticks()[::2])
This would only display every 2nd xtick.
If you wanted to only display every n-th tick you would use
ax.set_xticks(ax.get_xticks()[::n])
If you don't have a handle on ax
you can get one as ax = plt.gca()
.
Alternatively, you could specify the number of xticks to use with:
plt.locator_params(axis='x', nbins=10)