我正在使用matplotlib绘制条形图,当我尝试访问标签(在X轴和Y轴上)以更改它时,我遇到了问题。特别是,这段代码:
TAG POS={{!LOOP}} TYPE=A ATTR=TXT:*<SP>items EXTRACT=TXT
SET curPos EVAL("'{{!EXTRACT}}'.match(/Hide/) ? '' : {{!LOOP}};")
SET !ERRORIGNORE YES
TAG POS={{curPos}} TYPE=A ATTR=TXT:*<SP>items
SET !ERRORIGNORE NO
提供以下输出:
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)
根据要求,得到的数字具有“AAAAA”作为Y轴上每个标签的文本。我的问题是,虽然我能够正确设置标签,但显然我无法获取文本......并且文本应该存在,因为如果我不用“AAAAA”替换标签,我会得到下图:
如您所见,Y轴上有标签,我需要“获取”他们的文字。错误在哪里?
提前感谢您的帮助。
编辑:感谢MikeMüller的回答,我设法让它发挥作用。显然,在我的情况下调用draw()是不够的,我必须在使用savefig()保存图形后获取值。它可能取决于matplotlib的版本,我运行的是1.5.1而Mike正在运行1.5.0。我还将看一下FuncFormatter,如下面的tcaswell
所示答案 0 :(得分:4)
您需要首先渲染绘图以实际获取标签。添加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']