简体   繁体   中英

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.

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 . Eg

for label in ax.xaxis.get_tick_labels()[1::2]:
    print(len(label.get_text()))

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 (eg latex $ mathmode delimiters) as it is the length of the raw text string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM