Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

python - get_xticklabels() contains empty text instances

I am trying to rotate the x tick labels in a plot. I created a general function that plots in the style I want to plot. I do the following:

labels=ax2.get_xticklabels()
for i,label in labels:
   labels[i]=label.get_text()
ax2.set_xticklabels(labels, rotation=30)

This produced plots with no x_tick labels, so I dug deeper: I had it print the label as it was looping through and they were empty text instances. However, this is where it gets weird: When I just get the labels (labels=ax2.get_xticklabels()), and have the plot function return the list of text instances (return labels), the Text instances in the list do have the correct string, and the code above produces a list of strings as intended. I am not sure why the text instances are empty when I try to edit it inside of the function, but correct when I have the function return labels unedited. Any advice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I will answer according to the title in your question because I don't understand the explanation that follows it.

The tick labels are not populated until the figure is drawn.

plt.plot([1, 2])
ax = plt.gca()
labels = ax.get_xticklabels()
for label in labels:
    print(label)

Output:

Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')

When you call plt.draw() the tick labels are populated:

plt.plot([1, 2])
ax = plt.gca()
plt.draw()
labels = ax.get_xticklabels()
for label in labels:
    print(label)

Output:

Text(0,0,'')
Text(0,0,'0.0')
Text(0.2,0,'0.2')
Text(0.4,0,'0.4')
Text(0.6,0,'0.6')
Text(0.8,0,'0.8')
Text(1,0,'1.0')
Text(0,0,'')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...