matplotlib修剪刻度标签

时间:2015-01-12 20:21:52

标签: python matplotlib labels

我正在使用GridSpec绘制两个图形,一个在另一个之下,而在

之间没有间隙
gs = gridspec.GridSpec(3, 1)
gs.update(hspace=0., wspace=0.)
ax1 = plt.subplot(gs[0:2, 0])
ax2 = plt.subplot(gs[2, 0], sharex=ax1)

工作正常。但是,我想摆脱每个子图的顶部和底部刻度标签。 为此,我使用

nbins = len(ax1.get_yticklabels())
ax1.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='both'))
nbins = len(ax2.get_yticklabels())
ax2.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='both'))

在许多情况下工作正常。然而,在一些图中,要修剪的4个标记中的一个或多个仍然存在。我看着例如ax1.get_ylim()并注意到,而不是例如上限为10(如图中所示),实际上是10.000000000000002,我怀疑它是它的原因没有修剪。这是怎么发生的,我怎么能摆脱它?

这是一个例子:请注意,在图中,y轴被反转,没有标签被修剪,尽管它应该是。另请注意,由于某种原因,最低y标签设置为负位置,我不明白。 y刻度位置显示在图中文本的轴坐标中。在下图中,10.6处的标签不应该在那里!

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.ticker import MaxNLocator
import numpy as np

x1 = 1
y1 = 10.53839
err1 = 0.00865
x2 = 2
y2 = 9.43045
err2 = 0.00658

plt.clf()
fig = plt.figure(figsize=(6, 6))
gs = gridspec.GridSpec(3, 1)
gs.update(hspace=0., wspace=0.)
ax1 = plt.subplot(gs[0:2, 0])

ax1.errorbar(x1, y1, yerr=err1)
ax1.errorbar(x2, y2, yerr=err2)

ax1.invert_yaxis()

plt.setp(ax1.get_xticklabels(), visible=False)  # Remove x-labels between the plots
plt.xlim(0, 3)

ax2 = plt.subplot(gs[2, 0], sharex=ax1)

nbins = len(ax1.get_yticklabels())
ax1.yaxis.set_major_locator(MaxNLocator(nbins=8, prune='both'))
nbins = len(ax2.get_yticklabels())
ax2.yaxis.set_major_locator(MaxNLocator(nbins=6, prune='both'))

plt.savefig('prune.png')
plt.close()

prune

2 个答案:

答案 0 :(得分:2)

可能是,您正在查看上图的x轴上最左边的标签?如果是这样,这应该可以解决问题:

ax1.set_xticklabels([])

编辑:如果您使用sharex,则必须使用此功能,否则会在两个轴上删除刻度标签。

plt.setp(ax1.get_xticklabels(), visible=False)

答案 1 :(得分:0)

您可以尝试使用此功能:

import matplotlib.ticker as mticker

ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=7, prune='upper'))

我发现以上命令仅适用于y轴。

有人知道如何设置X轴报价器的最大限制吗?

相关问题