Issue
I was suffering a really bizarre issue with matplotlib's ax.transData.transform
in ipython. Basically, in the cell where fig, ax = plt.subplots()
is declared, running ax.transData.transform
for either the x
or y
axis is incorrect. However, if you run ax.transData.transform
in a later cell, it returns the correct values.
To demonstrate, here is code running the transformation in the cell where fig, ax = plt.subplots()
is declared:
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.set_ylim(-2,2)
ax.set_xlim(-5,5)
nsize=[x*100 for x in d]
yradius = (ax.transData.transform([(0,2)]) - ax.transData.transform([(0,1)]))[0,1]
print("yRadius: {}".format(yradius))
xradius = (ax.transData.transform([(2,0)]) - ax.transData.transform([(1,0)]))[0,0]
print("xRadius: {}".format(xradius))
The print output is
yRadius: 54.360000000000014
xRadius: 33.48000000000002
In a cell below the above cell, if I run
yradius = (ax.transData.transform([(0,2)]) - ax.transData.transform([(0,1)]))[0,1]
print("yRadius: {}".format(yradius))
xradius = (ax.transData.transform([(2,0)]) - ax.transData.transform([(1,0)]))[0,0]
print("xRadius: {}".format(xradius))
The output is
yRadius: 33.48000000000002
xRadius: 33.48000000000002
Why are the values of the two cells not the same? Although the xRadius
of the first cell matches the values of the bottom cell, the yRadius
is off. I think the bottom cell's values are correct, because since the ax
aspect is set to be equal, the two radii should be the same. Why is the yRadius
of the first cell wrong here? After trying out a bunch of different values for xlim
and ylim
I found the pattern that the minimum of the two radii in the first cell is correct, while the other one is off. This seems to me a very strange error. Is there any way of making it return the correct values in the initial cell?
Solution
Your observation is pretty accurate. What happens is simply that the equal aspect is only applied once the figure is drawn. This is the case for the second cell (because the figure is shown as output of the first). However in the first cell the axes still has its original extent.
Solution: Draw the figure before trying to obtain any coordinates from it,
fig.canvas.draw()
# Now obtain coordinates:
yradius = (ax.transData.transform([(0,2)]) - ax.transData.transform([(0,1)]))[0,1]
print("yRadius: {}".format(yradius))
xradius = (ax.transData.transform([(2,0)]) - ax.transData.transform([(1,0)]))[0,0]
print("xRadius: {}".format(xradius))
Answered By - ImportanceOfBeingErnest
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.