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

8

我希望用matlibplot轴绘制2个子图。由于这两个子图具有相同的ylabel和ticks,因此我想关闭第二个子图的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)

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

2个回答

11

我快速地搜索了一下,找到了答案:

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

4

一种稍微不同的解决方案是将刻度标签实际设置为''。以下操作可以去除所有y轴刻度标签和刻度线:

# 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接