python - 在 matplotlib 中将数据坐标转换为轴坐标

标签 python matplotlib transform

我正在尝试将数据点从数据坐标系转换为 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]

关于python - 在 matplotlib 中将数据坐标转换为轴坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62004022/

相关文章:

python - 元组列表分为两个列表

python - 可散列对象池

Python:获取类的源代码(使用检查)

python - 注释不会出现在 matplotlib 图中

xpath - Web.Config 转换 xml 注释

javascript - 如何使用 Javascript 精确设置动态样式转换?

python - 使用 __getattr__ 会导致 TypeError : 'str' object is not callable - Python 2. 7

python - Matplotlib/seaborn 直方图对分组箱使用不同的颜色

python - 如何使用 matplotlib 绘制 HSV 色轮

c# - Unity3D:将 child 移动到 parent 的轨道上