Reputation: 2058
I am trying to convert data points from the data coordinate system to the axes coordinate system in matplotlib.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# this is in data coordinates
point = (1000, 1000)
# this takes us from the data coordinates to the display coordinates.
trans = ax.transData.transform(point)
print(trans) # so far so good.
# this should take us from the display coordinates to the axes coordinates.
trans = ax.transAxes.inverted().transform(trans)
# the same but in one line
# trans = (ax.transData + ax.transAxes.inverted()).transform(point)
print(trans) # why did it transform back to the data coordinates? it
# returns [1000, 1000], while I expected [0.5, 0.5]
ax.set_xlim(0, 2000)
ax.set_ylim(0, 2000)
ax.plot(*trans, 'o', transform=ax.transAxes)
# ax.plot(*point, 'o')
fig.show()
I read the transformation tutorial and tried the solution presented in this answer, which my code is based on, but it doesn't work. I just can't figure out why, and it's driving me nuts. I'm sure there is an easy solution to it, but I just don't see it.
Upvotes: 3
Views: 4725
Reputation: 5913
The transform is working, its just that when you start, the default axes limits are 0, 1, and it doesn't know ahead of time that you plan to change the limits:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# this is in data coordinates
point = (1000, 1000)
trans = ax.transData.transform(point)
trans = ax.transAxes.inverted().transform(trans)
print(ax.get_xlim(), trans)
ax.set_xlim(0, 2000)
ax.set_ylim(0, 2000)
trans = ax.transData.transform(point)
trans = ax.transAxes.inverted().transform(trans)
print(ax.get_xlim(), trans)
yields:
(0.0, 1.0) [1000. 1000.]
(0.0, 2000.0) [0.5 0.5]
Upvotes: 6
Reputation: 2058
Ok, I found the (obvious) problem. In order for the transformation to work, I need to set the axes limits before calling the transformation, which makes sense, I guess.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_xlim(0, 2000)
ax.set_ylim(0, 2000)
point = (1000, 1000)
trans = (ax.transData + ax.transAxes.inverted()).transform(point)
print(trans)
ax.plot(*trans, 'o', transform=ax.transAxes)
# ax.plot(*point, 'o')
fig.show()
Upvotes: 4