matplotlib 中 get_yticklabels 函数存在问题

4

我正在使用matplotlib绘制条形图,但是当我尝试访问标签(无论是X轴还是Y轴)以更改它们时,遇到了问题。特别是这段代码:

fig = plot.figure(figsize=(16,12), dpi=(300))
ax1 = fig.add_subplot(111)
ax1.set_ylabel("simulated quantity")
ax1.set_xlabel("simulated peptides - from most to least abundant")

# create the bars, and set a different color for the bars referring to experimental peptides
barlist = ax1.bar( numpy.arange(len(quantities)), [numpy.log10(x) for x in quantities] )
for index, peptide in enumerate(peptides) :
        if peptide in experimentalPeptidesP or peptide in experimentalPeptidesUP :
                barlist[index].set_color('b')

labelsY = ax1.get_yticklabels(which='both')
print "These are the label objects on the Y axis:", labelsY
print "These are the labels on the Y axis:", [item.get_text() for item in ax1.get_xticklabels(    which='both')]
for label in labelsY : label.set_text("AAAAA")
ax1.set_yticklabels(labelsY)

给出以下输出:
These are the label objects on the Y axis: <a list of 8 Text yticklabel objects>
These are the labels on the Y axis: [u'', u'', u'', u'', u'', u'']

结果图上每个Y轴标签的文本都是“AAAAA”,就像要求的一样。我的问题是,虽然我能够正确地设置标签,但显然我无法获取它们的文本……而文本应该存在,因为如果我不用“AAAAA”替换标签,我会得到以下图形: enter image description here
如您所见,Y轴上有标签,我需要“获取”它们的文本。哪里出了错?
非常感谢您的帮助。
编辑:由于Mike Müller的答案,我设法使其工作。显然,在我的情况下,仅调用draw()是不够的,我必须在使用savefig()保存图形后获取值。这可能取决于matplotlib的版本,我正在运行1.5.1,而Mike正在运行1.5.0。我还将查看tcaswell建议的FuncFormatter。

因为这些对象被替换为ticker/formatter机制。你实际上想做什么? - tacaswell
阅读自动放置在Y轴上的标签(如上例中的“0.0”,“0.5”,“1.0”等),并将它们替换为pow(10, 0.0),pow(10, 0.5),pow(10, 1.0)等。 - Alberto
Mpl内置了对数坐标轴,可以为您处理这种情况。否则,请使用FuncFormatter。 - tacaswell
1个回答

7

您需要先渲染绘图,才能获得标签。添加draw()即可:

plot.draw()
labelsY = ax1.get_yticklabels(which='both')

没有:

from matplotlib import pyplot as plt

fig = plt.figure(figsize=(16,12), dpi=(300))
ax1 = fig.add_subplot(111)
p = ax1.bar(range(5), range(5))

>>> [item.get_text() for item in ax1.get_yticklabels(which='both')]
['', '', '', '', '', '', '', '', '']

使用draw()函数:

from matplotlib import pyplot as plt

fig = plt.figure(figsize=(16,12), dpi=(300))
ax1 = fig.add_subplot(111)
p = ax1.bar(range(5), range(5))
plt.draw()

>>> [item.get_text() for item in ax1.get_yticklabels(which='both')]
['0.0', '0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0']

嗨!我尝试在收集标签之前添加“plot.draw()”行,但显然结果是相同的。我得到了8个对象,但无法可视化它们的文本。 - Alberto
你使用的是哪个版本?我用1.5.0让它工作了。 - Mike Müller
1.5.1;但是感谢您的建议,我设法让它工作了。显然,我只需要在使用savefig()保存图形后获取标签,文本就会出现...这意味着我必须保存两次:-D 奇怪...也许是因为我从未调用show()? - Alberto
谢谢提示。复制粘贴问题已解决。 - Mike Müller

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