gpt4 book ai didi

python - Matplotlib 坐标变换

转载 作者:太空宇宙 更新时间:2023-11-03 14:55:31 26 4
gpt4 key购买 nike

我试图理解这段代码:

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 .

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

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

最佳答案

说明

add_inset(ax, rect) 方法中,rect 是轴坐标中的矩形。这是有道理的,因为您经常想要指定插图相对于其所在轴的位置。
然而,为了以后能够创建新的轴,轴的位置需要在图形坐标中已知,然后可以将其提供给 fig.add_axes(figurecoordinates)。所以需要的是从轴坐标到图形坐标的坐标变换。这是在此处分两步执行的:

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

这两个步骤的过程可以进一步压缩成一个单一的转换

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

阅读 matplotlib transformation tutorial 可能会有兴趣关于转换的工作原理。

备选方案

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

import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1.inset_locator as il

fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(4,4))
ax1.plot([1,2,3],[2.2,2,3])

# set the inset at upper left (loc=2) with width, height=0.5,0.4
axins = il.inset_axes(ax1, "50%", "40%", loc=2, borderpad=1)
axins.scatter([1,2,3],[3,2,3])

# set the inset at 0.2,0.5, with width, height=0.8,0.4
# in parent axes coordinates
axins2 = il.inset_axes(ax2, "100%", "100%", loc=3, borderpad=0,
bbox_to_anchor=(0.2,0.5,0.7,0.4),bbox_transform=ax2.transAxes,)
axins2.scatter([1,2,3],[3,2,3])

plt.show()

enter image description here

关于python - Matplotlib 坐标变换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42932908/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com