Stephen Strosko
Stephen Strosko

Reputation: 665

Accessing Matplotlib Text Object Label Text

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

Answers (2)

tmdavison
tmdavison

Reputation: 69076

The labels 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

Gasvom
Gasvom

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

Related Questions