如何关闭matlibplot轴的刻度和标记?

时间:2012-07-22 21:38:30

标签: python matplotlib axes

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

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)
BTW,X轴标记重叠,不确定是否有整齐的解决方案。 (解决方案可能是使每个子图中的最后一个标记不可见,除了最后一个,但不确定如何)。谢谢!

2 个答案:

答案 0 :(得分:10)

快速google,我找到了答案:

plt.setp(ax2.get_yticklabels(), visible=False)
ax2.yaxis.set_tick_params(size=0)
ax1.yaxis.tick_left()

答案 1 :(得分:4)

稍微不同的解决方案可能是将ticklabels实际设置为''。以下将删除所有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)