在matplotlib中将数据坐标转换为轴坐标
问题描述
我正在尝试将数据点从数据坐标系转换到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()
我阅读了transformation tutorial,并尝试了我的代码所基于的this answer中提供的解决方案,但它不起作用。我就是想不通为什么,这快把我逼疯了。我相信有一个简单的解决办法,但我就是看不出来。
解决方案
转换正在工作,只是当您启动时,默认轴限制为0、1,并且它不知道您计划更改这些限制:
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)
收益率:
(0.0, 1.0) [1000. 1000.]
(0.0, 2000.0) [0.5 0.5]
相关文章