Reputation: 3913
How to get tick labels for a matplotlib axis without invoking plt.show
first? I am trying to set up a bunch of subplots, manipulate their window limits and tick labels, and then bring it all on the screen together. However, get_xticklabels()
method returns empty strings unless plt.show
is called:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.plot(1, 1)
print("before plt.show(): {}".format(ax.get_xticklabels()[0].get_text()))
plt.show()
print("after plt.show(): {}".format(ax.get_xticklabels()[0].get_text()))
Output:
In [33]: %run plt_premature_ticks.py
before plt.show():
after plt.show(): 0.94
Is it not an expected behavior to try getting the labels before the figure is actually shown?
Upvotes: 0
Views: 1995
Reputation: 3913
While HYRY gave a correct answer to the original question, I've come across a few cases where one would need to call the draw
method of an axis instance to get the tick labels visible. In that case, the following should be called:
renderer = fig.canvas.get_renderer()
ax.draw(renderer)
Upvotes: 1
Reputation: 97331
Add fig.canvas.draw()
before ax.get_xticklabels()
:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.plot(1, 1)
fig.canvas.draw()
print("before plt.show(): {}".format(ax.get_xticklabels()[0].get_text()))
plt.show()
print("after plt.show(): {}".format(ax.get_xticklabels()[0].get_text()))
Upvotes: 4