Home > OS >  Matplotlib: get_xticks() gives wrong result after using ax.set_aspect()
Matplotlib: get_xticks() gives wrong result after using ax.set_aspect()

Time:09-06

I'm making a scatter plot, then using ax.set_aspect('equal') (which changes the number and locations of the ticks on the x-axis), and then I try to access the locations of the ticks with ax.get_xticks(). However, this gives me the old locations of the ticks, before set_aspect resized the axes. See the following code:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
fig = plt.figure()
ax = plt.axes()
ax.scatter(x, 2*x)
print(ax.get_xticks())
ax.set_aspect('equal')
print(ax.get_xticks())

This outputs:

[-2.  0.  2.  4.  6.  8. 10.]
[-2.  0.  2.  4.  6.  8. 10.]

which shows the result does not change.

The code generates the following plot, which shows the x-ticks definitely have changed: scatter plot

How do I access the new locations of the x-ticks?

CodePudding user response:

The aspect ratio isn't applied until draw time for reasons of efficiency. You can do:

print(ax.get_xticks())
ax.set_aspect('equal')
ax.apply_aspect()
print(ax.get_xticks())

and you will get the new ticks.

  • Related