2016-02-26 187 views
0

我正在用matplotlib绘制几个相邻的面板。我遇到了一些轴标签在面板会合处重叠的问题。下面是一个最小工作示例和示例图像。如何删除matplotlib中的一个刻度轴标签

import matplotlib.pyplot as plt 

fig = plt.figure(figsize=(4,8)) 
ax1 = fig.add_axes([.25,.5,.5,.25]) 
ax2 = fig.add_axes([.25,.25,.5,.25]) 

ax1.set_xticklabels([]) 

fig.savefig("temp.pdf") 

enter image description here

正如你可以在图像中看到,顶面板的0.0和底部面板的1.0是在同一个地方。我试图让底部面板的1.0不显示,但仍然显示轴上剩余的标签。没有我试过的工作。事我曾尝试:

#This just doesn't do anything 
from matplotlib.ticker import MaxNLocator 
ax3.xaxis.set_major_locator(MaxNLocator(prune='upper')) 

#This produces the image shown below 
labels = [item for item in ax2.get_yticklabels()] 
labels[-1].text = '' 
ax2.set_yticklabels(labels) 

#This also produces the image shown below 
labels = ax2.get_yticklabels() 
labels[-1].set_text('') 
ax2.set_yticklabels(labels) 

enter image description here

上面的图象是由最后两个代码的三个块的紧接在图像之前产生的。无论是否包含行labels[-1].text = '',都会出现奇怪的y轴标签。

回答

2

您将需要抓取所有轴的yticklabels,然后使用除最后一个以外的所有yticklabels进行设置。这里重要的一点是(特别是对于较新版本的matplotlib),您必须显示图形并在之前刷新画布以获取ytick标签,以便它们的默认位置已经被计算出来。

import matplotlib.pyplot as plt 

fig = plt.figure(figsize=(4,8)) 
ax1 = fig.add_axes([.25,.5,.5,.25]) 
ax2 = fig.add_axes([.25,.25,.5,.25]) 

ax1.set_xticklabels([]) 

# Important to render initial ytick labels 
fig.show() 
fig.canvas.draw() 

# Remove the last ytick label 
labels = [tick.get_text() for tick in ax2.get_yticklabels()] 
ax2.set_yticklabels(labels[:-1]) 

# Refresh the canvas to reflect the change 
fig.canvas.draw() 

注:在我以前的代码中,我使用的是fig.savefig()呼叫改变蜱调试以前的事情,这迫使默认ytick标签渲染和生成。

enter image description here

+0

无论你的建议改变我的y轴标签'文本(0,0,U “)”)'。我在上面编辑的问题中展示了这个图片。也许我在我的matplotlibrc文件中设置的东西是搞砸了?我尝试关闭matplotlibrc文件中的所有内容,但问题仍然存在。更重要的是,无论是否包含'labels [-1] .set_text('')',我都会得到同样奇怪的y轴标签。 – Joshua

+0

@Joshua嗯不知道那里发生了什么。我已经用不应该给您带来任何问题的解决方案更新了我的答案。 – Suever

+0

您的更新使我的轴标签完全消失。当我在你的代码块的第一行之后'打印标签'时,我得到一个空字符串列表:'[u'',u'',u'',u'',u'',u''] ' – Joshua

相关问题