Reputation: 665
Attempting to access the length of a matplotlib axis label with this code:
for label in ax.xaxis.get_ticklabels()[1::2]:
print(len(label))
However I am getting an error that the object does not have a length attribute. print(label[2])
also errors out with a similar error.
Upvotes: 28
Views: 28716
Reputation: 69076
The label
s you are iterating over from get_ticklabels()
are matplotlib.text.Text
objects. To access the actual text in that object, you can use get_text()
.
So, something like this should work:
for label in ax.xaxis.get_ticklabels()[1::2]:
print(len(label.get_text()))
Note that this length may include special characters (e.g. latex $
mathmode delimiters) as it is the length of the raw text string
Upvotes: 11
Reputation: 651
Matplotlib's text objects can't be accessed through standard indexing - what you're looking for is the get_text()
attribute found in the text object documentation. E.g.
for label in ax.xaxis.get_tick_labels()[1::2]:
print(len(label.get_text()))
Upvotes: 45