8

我想使用 matlibplot 轴绘制 2 个子图。由于这两个子图具有相同的 ylabel 和刻度,我想关闭第二个子图的刻度和标记。以下是我的简短脚本:

import matplotlib.pyplot as plt
ax1=plt.axes([0.1,0.1,0.4,0.8])
ax1.plot(X1,Y1)
ax2=plt.axes([0.5,0.1,0.4,0.8])
ax2.plot(X2,Y2)

顺便说一句,X轴标记重叠,不确定是否有一个整洁的解决方案。(一种解决方案可能是使每个子图的最后一个标记不可见,除了最后一个,但不确定如何)。谢谢!

4

2 回答 2

11

一个快速的谷歌,我找到了答案:

plt.setp(ax2.get_yticklabels(), visible=False)
ax2.yaxis.set_tick_params(size=0)
ax1.yaxis.tick_left()
于 2012-07-22T22:07:08.147 回答
4

稍微不同的解决方案可能是将刻度标签实际设置为“”。以下将摆脱所有 y-ticklabels 和刻度线:

# This is from @pelson's answer
plt.setp(ax2.get_yticklabels(), visible=False)

# This actually hides the ticklines instead of setting their size to 0
# I can never get the size=0 setting to work, unsure why
plt.setp(ax2.get_yticklines(),visible=False)

# This hides the right side y-ticks on ax1, because I can never get tick_left() to work
# yticklines alternate sides, starting on the left and going from bottom to top
# thus, we must start with "1" for the index and select every other tickline
plt.setp(ax1.get_yticklines()[1::2],visible=False)

现在摆脱 x 轴的最后一个刻度线和标签

# I used a for loop only because it's shorter
for ax in [ax1, ax2]:
    plt.setp(ax.get_xticklabels()[-1], visible=False)
    plt.setp(ax.get_xticklines()[-2:], visible=False)
于 2012-07-24T01:34:38.233 回答