29

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.

2 Answers 2

46

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()))
Sign up to request clarification or add additional context in comments.

2 Comments

Does anyone know why the maplotlib text objects use a '-' that can't convert to a number? ``` In [66]: secax.get_yticklabels()[0].get_text() Out[66]: '−2.5' In [67]: type(a.get_text()) Out[67]: str In [68]: type(a.get_text()), a Out[68]: (str, Text(1, -2.5, '−2.5')) In [69]: float(a.get_text()) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-69-d347a578a778> in <module> ----> 1 float(a.get_text()) ValueError: could not convert string to float: '−2.5' ```
@tsherwen For whatever reason, the '−' used by matplotlib is a different minus character (unicode 8722) compared to the regular '-' (unicode 45). If you do float(a.replace('−', '-').get_text()), that should work
11

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.