X-axis tick labels are too dense when drawing plots with matplotlib
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?
Solution 1:
A quick dirty solution would be the following:
ax.set_xticks(ax.get_xticks()[::2])
This would only display every second 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)
Solution 2:
An alternate solution could be as below:
x = df['Date']
y = df['Value']
# Risize the figure (optional)
plt.figure(figsize=(20,5))
# Plot the x and y values on the graph
plt.plot(x, y)
# Here you specify the ticks you want to display
# You can also specify rotation for the tick labels in degrees or with keywords.
plt.xticks(x[::5], rotation='vertical')
# Add margins (padding) so that markers don't get clipped by the axes
plt.margins(0.2)
# Display the graph
plt.show()