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

Question:

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?

Asked By: Albacete

||

Answers:

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.

Answered By: Jody Klymak
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.