Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

x-axis that looks fine

And here is an example of an x axis which is too dense because the data spans on a long period of time:

x-axis labels that are too dense

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?

like image 242
Canol Gökel Avatar asked Feb 20 '19 09:02

Canol Gökel


People also ask

How do you change X ticks in MatPlotLib?

Matplotlib histogram set_xticks To change the default x ticks, use set_xticks() function in Matplotlib.

How do I spread X-axis labels in MatPlotLib?

To increase the space for X-axis labels in Matplotlib, we can use the spacing variable in subplots_adjust() method's argument.

How do you reduce the density of X ticks in Seaborn?

To decrease the density of x-ticks in Seaborn, we can use set_visible=False for odd positions.


2 Answers

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)

like image 90
jwalton Avatar answered Oct 01 '22 16:10

jwalton


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()

enter image description here

like image 32
R.K Avatar answered Oct 01 '22 17:10

R.K