简体   繁体   English

从数据坐标转换为 matplotlib 中的轴坐标

[英]Convert from data coordinates to axes coordinates in matplotlib

I am trying to convert data points from the data coordinate system to the axes coordinate system in 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()

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.我确信有一个简单的解决方案,但我只是看不到它。

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:转换正在工作,只是当您开始时,默认轴限制为 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)

yields:产量:

(0.0, 1.0) [1000. 1000.]
(0.0, 2000.0) [0.5 0.5]

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM