0

I find that when I change the format of the x-axis tick labels, the values of the labels are not correct when I zoom into an area on the graph

# create a simple plot   
x=arange(6e-6,7e-6,100e-9)
y=random.rand(len(x))    
f=plt.figure(1)
plt.plot(x,y)
plt.grid()
f1=plt.figure(1)
plt.plot(x,y)

#Then I change the format of the labels:
x=f.get_axes()[0]
xlabels = [format(label, ',.1f') for label in ax.get_xticks()]
ax.set_xticklabels(xlabels)

#and when I zoom in, the peak is not at the same x-location as before the zoom

before label formatting

after label formatting

when zoomed in

user28846
  • 1
  • 1
  • I cannot reproduce this. One cannot help you without a [Minimal, **Complete**, and **Verifiable** example](https://stackoverflow.com/help/mcve) – Diziet Asahi May 15 '19 at 20:14
  • I'm confused: your `x` is `[6.0e-06, 6.1e-06, 6.2e-06, ...]`, yet you want your `xticklabels` to be formatted as `',.1f'`, which would return `[0.0, 0.0, 0.0, …]`? Do you perhaps want to `ax.plot(x*10e5,y)` instead? The way you are applying `xticklabels` *ignores* what the xticks actually are and instead overwrites them with the *fixed values* of the initial `ax.get_xticks()`. If they initially were `[6.0, 6.1, 6.2, ….] `, then these labels will be applied to the plot *no matter what the actual, current xticks are*, i.e. they will not "move" when you move the plot around. – Asmus May 20 '19 at 06:14
  • Perhaps you'd rather use [this](https://stackoverflow.com/a/53482674/565489), i.e. a `matplotlib.ticker.StrMethodFormatter` – Asmus May 20 '19 at 06:21

0 Answers0