ncRubert
ncRubert

Reputation: 3922

Overlapping y-axis tick label and x-axis tick label in matplotlib

If I create a plot with matplotlib using the following code:

import numpy as np
from matplotlib import pyplot as plt
xx = np.arange(0,5, .5)
yy = np.random.random( len(xx) )
plt.plot(xx,yy)
plt.imshow()

I get a result that looks like the attached image. The problem is the bottom-most y-tick label overlaps the left-most x-tick label. This looks unprofessional. I was wondering if there was an automatic way to delete the bottom-most y-tick label, so I don't have the overlap problem. The fewer lines of code, the better. enter image description here

Upvotes: 40

Views: 33408

Answers (4)

enrico.bacis
enrico.bacis

Reputation: 31474

You can pad the ticks on the x-axis:

ax.tick_params(axis='x', pad=15)

Replace ax with plt.gca() if you haven't stored the variable ax for the current figure.

You can also pad both the axes removing the axis parameter.

Upvotes: 23

Marius
Marius

Reputation: 553

A very elegant way to fix the overlapping problem is increasing the padding of the x- and y-tick labels (i.e. the distance to the axis). Leaving out the corner most label might not always be wanted. In my opinion, in general it looks nice if the labels are a little bit farther from the axis than given by the default configuration.

The padding can be changed via the matplotlibrc file or in your plot script by using the commands

import matplotlib as mpl

mpl.rcParams['xtick.major.pad'] = 8
mpl.rcParams['ytick.major.pad'] = 8

Most times, a padding of 6 is also sufficient.

Upvotes: 7

mechanical_meat
mechanical_meat

Reputation: 169264

In the ticker module there is a class called MaxNLocator that can take a prune kwarg.
Using that you can remove the first tick:

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
xx = np.arange(0,5, .5)
yy = np.random.random( len(xx) )
plt.plot(xx,yy)
plt.gca().xaxis.set_major_locator(MaxNLocator(prune='lower'))
plt.show()

Result:

enter image description here

Upvotes: 39

ACV
ACV

Reputation: 1965

This is answered in detail here. Basically, you use something like this:

plt.xticks([list of tick locations], [list of tick lables])

Upvotes: 2

Related Questions