简体   繁体   English

在matplotlib中重叠的y轴刻度标签和x轴刻度标签

[英]Overlapping y-axis tick label and x-axis tick label in matplotlib

If I create a plot with matplotlib using the following code: 如果我使用以下代码使用matplotlib创建绘图:

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. 问题是最底部的y-tick标签与最左边的x-tick标签重叠。 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. 我想知道是否有一种自动方式来删除最底部的y-tick标签,所以我没有重叠问题。 The fewer lines of code, the better. 代码行越少越好。 在此输入图像描述

In the ticker module there is a class called MaxNLocator that can take a prune kwarg. 在自动收报机模块中有一个名为MaxNLocator的类,它可以采用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: 您可以在x轴上填充刻度:

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

Replace ax with plt.gca() if you haven't stored the variable ax for the current figure. 如果没有为当前数字存储变量ax ,请用plt.gca()替换ax

You can also pad both the axes removing the axis parameter. 您也可以填充两个轴,删除axis参数。

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). 解决重叠问题的一种非常优雅的方法是增加x和y刻度标签的填充(即到轴的距离)。 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 可以使用命令通过matplotlibrc文件或绘图脚本更改填充

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. 大多数情况下,填充6也足够了。

This is answered in detail here . 这在详细回答了这里 Basically, you use something like this: 基本上,你使用这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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