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

Question:

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

Asked By: ncRubert

||

Answers:

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

plt.xticks([list of tick locations], [list of tick lables])
Answered By: ACV

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

Answered By: mechanical_meat

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.

Answered By: Marius

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.

Answered By: enrico.bacis
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.