Getting empty tick labels before showing a plot in Matplotlib Getting empty tick labels before showing a plot in Matplotlib python python

Getting empty tick labels before showing a plot in Matplotlib


You've correctly identified the problem: before you call plt.show() nothing is explicitly set. This is because matplotlib avoids static positioning of the ticks unless it has to, because you're likely to want to interact with it: if you can ax.set_xlim() for example.

In your case, you can draw the figure canvas with fig.canvas.draw() to trigger tick positioning, so you can retrieve their value.

Alternatively, you can explicity set the xticks that will in turn set the the axis to FixedFormatter and FixedLocator and achieve the same result.

import numpy as npimport matplotlib.pyplot as pltx = np.linspace(0,2*np.pi,100)y = np.sin(x)**2fig, ax = plt.subplots()ax.plot(x,y)ax.set_xlim(0,6)# Must draw the canvas to position the ticksfig.canvas.draw()# Or Alternatively#ax.set_xticklabels(ax.get_xticks())labels = ax.get_xticklabels()for label in labels:    print(label.get_text())plt.show()Out:0123456


As Julien Marrec, you have to call fig.canvas.draw().Good thing is it doesn't wait for input after opening window and directly displays the chart(or returns control to next line in code)

So I made a workaround here:

# First call the .draw() function and take whatever values your need.fig.canvas.draw()x_lab = axes.get_xticklabels()y_lab = axes.get_yticklabels()z_lab = axes.get_zticklabels()# Now we close the figure since we are done getting values# This will be a fast process and look like figure never openedplt.close()