在matplotlib中将数据坐标转换为轴坐标 [英] Convert from data coordinates to axes coordinates in matplotlib

查看:52
本文介绍了在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]

这篇关于在matplotlib中将数据坐标转换为轴坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆