Matplotlib坐标转换

2024-10-06 10:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解以下代码片段:

def add_inset(ax, rect, *args, **kwargs):
    box = ax.get_position()
    inax_position = ax.transAxes.transform(rect[0:2])
    infig_position = ax.figure.transFigure.inverted().transform(inax_position)
    new_rect = list(infig_position) + [box.width * rect[2], box.height * rect[3]]
    return fig.add_axes(new_rect, *args, **kwargs)

此代码将向现有地物添加插图。看起来像这样: enter image description here

原始代码来自this notebook file。在

我不明白为什么需要两个坐标变换:

^{pr2}$

Tags: 代码rectboxaddnewgetdefargs
1条回答
网友
1楼 · 发布于 2024-10-06 10:30:06

说明

add_inset(ax, rect)方法中,rect是坐标轴上的矩形。这是有意义的,因为您通常需要指定inset相对于其所在轴的位置。
但是,为了以后能够创建一个新的轴,轴的位置需要在图形坐标中已知,然后可以给fig.add_axes(figurecoordinates)。 所以需要的是从坐标轴坐标到图形坐标的坐标变换。此过程分两步进行:

  1. 使用transAxes从轴坐标转换为显示坐标。在
  2. 使用transFigure的逆运算将显示坐标转换为图形坐标。在

这两个步骤可以进一步浓缩在一个单一的转换,如

mytrans = ax.transAxes + ax.figure.transFigure.inverted()
infig_position = mytrans.transform(rect[0:2])

阅读matplotlibtransformation tutorial中有关转换如何工作的内容可能会很有趣。在

替代品

上面的方法可能不是放置插图的最明显的方法。Matplotlib本身提供了一些工具。一种方便的方法是mpl_toolkits.axes_grid1.inset_locator。下面是在轴坐标中创建插入时使用其inset_axes方法的两种方法。在

^{pr2}$

enter image description here

相关问题 更多 >