简体   繁体   中英

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. 在此输入图像描述

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:

在此输入图像描述

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.

A very elegant way to fix the overlapping problem is increasing the padding of the x- and y-tick labels (ie 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM