最后一个次刻度未绘制 - Pyplot

2 投票
1 回答
3210 浏览
提问于 2025-04-18 01:12

我正在尝试在同一个图形中绘制两个子图,并且它们共享x轴。但是,我无法绘制最后一个小的x刻度线。我不知道这个问题是怎么来的,但我用随机数据复现了这个现象。

我使用的系统是python2.7和matplotlib v1.2.1

下面是我用来复现错误的最小示例:

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

xdat = np.linspace(0,6.6,endpoint=True)
ydat1 = np.random.rand(50)*500
ydat2 = np.random.rand(50)*4

fig = plt.figure(figsize=(6,8), dpi=72)
gs = gridspec.GridSpec(2,1, height_ratios=[3,1])
fig.subplots_adjust(hspace=0.0)
ax1 = plt.subplot(gs[0])

ax1.plot(xdat, ydat1)
ax1.set_xlim(0,6.6)
ax1.set_xticks(range(0,8,1))
ax1.minorticks_on()
[label.set_visible(False) for label in ax1.get_xticklabels() ]  # Make tick labels invisible

ax2 = plt.subplot(gs[1], sharex=ax1)
ax2.plot(xdat, ydat2, 'r-')
ax2.yaxis.set_major_locator(MaxNLocator(nbins=5, steps=[1,2,4,5,10], symmetric=False, prune='upper'))
plt.show()

我得到了以下图像:

示例图,最后一个小刻度线缺失

我不知道这是否是一个bug,或者是否有简单的方法来解决这个问题(比如更新matplotlib)。

1 个回答

5

我还没找到这个问题的具体原因,不过版本 1.3.1 也有同样的情况。

一个解决办法是手动设置小刻度,可以通过添加 ax2.xaxis.set_ticks(np.hstack((ax2.xaxis.get_ticklocs(minor=True), 6.4)), minor=True) 来实现,其中 6.4 是最后一个小刻度。

在这里输入图片描述

或者你可以把 xlim 设置得稍微大一点,这样最后一个刻度就会显示出来。可以用 ax2.set_xlim((0,6.6)) 来设置。默认的范围是 (0.0, 6.5999999999999996)

我觉得这可以算作一个bug。

撰写回答