【问题标题】:Convert from data coordinates to axes coordinates in matplotlib在 matplotlib 中从数据坐标转换为轴坐标
【发布时间】:2020-05-25 14:03:53
【问题描述】:

我正在尝试将数据点从数据坐标系转换为 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 中提出的解决方案,这是我的代码所基于的,但它不起作用。我只是不知道为什么,这让我发疯。我确信有一个简单的解决方案,但我只是没有看到它。

【问题讨论】:

  • 你到底想做什么?从您的帖子或代码中不清楚。
  • 我正在尝试将数据坐标(1000, 1000) 转换为坐标轴坐标,即在这种情况下,预期结果将是(0.5, 0.5),因为坐标轴坐标从(0, 0) 变为(1, 1) .
  • 我的意思是你只想要一对数字吗?你在那里有一个情节声明。为什么?它只是您想要正确的打印语句吗?
  • 不,我希望转换正确。我是否打印或绘制该信息无关紧要。

标签: python matplotlib transform


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    好的,我发现了(明显的)问题。为了使转换起作用,我需要在调用转换之前设置轴限制,我猜这是有道理的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多