Description
Bug report
Bug summary
My issue is closely related to the one here.
I need to access the ticklabels before writing my plot to a file, but when being non interactive there appears to be no way of forcing the generation of ticklabels, or is there? Both fig.canvas.draw()
and matplotlib.pyplot.draw()
have no effect.
Of course I could generate my own ticklabels, using ax.set_xticklabels(ax.get_xticks())
but I very much like the default formatting of ticks so I would like to rely on matplotlib here.
In the code below method 0 is what I would label the clean solution whereas all other implementations are workarounds, necessary to compensate for the difference of the behaviors of interactive vs non interactive backends. I find the dependence on the interactiveness of the backend problematic. This is because what I often do is to develop a plotting code using an interactive backend and when it's ready I apply it to big data on a HPC were I'm not always provided interactive backends.
Code for reproduction
#!/usr/bin/env python3
import matplotlib
matplotlib.use('pdf')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
print('backend:',matplotlib.get_backend())
x = np.linspace(0,3,100)
y = np.sin(x)**2
method = 0
while True:
fig, ax = plt.subplots()
ax.plot(x,y)
if method == 0:
fig.canvas.draw()
plt.draw()
elif method == 1:
ax.xaxis.set_major_locator(ticker.AutoLocator())
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
elif method == 2:
ax.set_xticklabels(ax.get_xticks())
elif method == 3:
ax.set_xticklabels([ ticker.ScalarFormatter().format_data(tick) for tick in ax.get_xticks() ])
elif method == 4:
ax.set_xticklabels([ '{:g}'.format(tick) for tick in ax.get_xticks() ])
else:
break
print('method {:d} :'.format(method), end='')
print([ label.get_text() for label in ax.get_xticklabels() ] )
method += 1
Actual outcome
backend: pdf
method 0 :['', '', '', '', '', '', '', '', '']
method 1 :['', '', '', '', '', '', '', '', '']
method 2 :['-0.5', '0.0', '0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5']
method 3 :['−5e−1', '0', '5e−1', '1', '1.5', '2', '2.5', '3', '3.5']
method 4 :['-0.5', '0', '0.5', '1', '1.5', '2', '2.5', '3', '3.5']
Expected outcome
backend: pdf
method 0 :['−0.5', '0.0', '0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5']
method 1 :['', '', '', '', '', '', '', '', '']
method 2 :['-0.5', '0.0', '0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5']
method 3 :['−5e−1', '0', '5e−1', '1', '1.5', '2', '2.5', '3', '3.5']
method 4 :['-0.5', '0', '0.5', '1', '1.5', '2', '2.5', '3', '3.5']
Which (apart from the first line of course) is obtained when using an interactive backend.
Matplotlib version
- Operating system: Ubuntu 16.04.5 LTS 64-bit
- Matplotlib version: 3.0.2 (conda, build: py36_1002, channel: conda-forge)
- Matplotlib backend (
print(matplotlib.get_backend())
): pdf - Python version: 3.6.8 (conda, build: h0371630_0)