Reputation: 372
I am using matplotlib to plot a bar graph, and I am experiencing an issue when I try to access the labels (both on the X and Y axis) to change them. In particular, this code:
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)
Gives the following output:
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'']
And the resulting figure has "AAAAA" as the text of every label on the Y axis, as requested. My issue is, while I am able to correctly SET the labels, apparently I cannot GET their text...and the text should exist, because if I don't replace the labels with "AAAAA" I get the following figure:
As you can see, there are labels on the Y axis, and I'd need to "get" their text. Where is the error?
Thank you in advance for your help.
EDIT: Thanks to Mike Müller's answer, I managed to make it work. Apparently, in my case invoking draw() is not enough, I have to get the values AFTER saving the figure using savefig(). It might depend on matplotlib's version, I am running 1.5.1 and Mike is running 1.5.0 . I will also take a look at FuncFormatter, as suggested below by tcaswell
Upvotes: 4
Views: 3644
Reputation: 85492
You need to render the plot first to actually get labels. Adding a draw()
works:
plot.draw()
labelsY = ax1.get_yticklabels(which='both')
Without:
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')]
['', '', '', '', '', '', '', '', '']
and with 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']
Upvotes: 7