matplotlib 轴与 inset_axes 之间的差距

Gap between matplotlib axis and inset_axes

我想添加一个 inset_axis 与周围的轴对齐。因此,我将 bbox_to_anchor=(0, 0.5) 参数的第一个值设置为零。然而,它们的 y 轴之间总是有一个非常小的间隙,见图:

import matplotlib.patches
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

fig, ax = plt.subplots(figsize=(5, 7))

background_geometry = matplotlib.patches.Rectangle(
    xy=(0, 0),
    width=5,
    height=7,
    linewidth=0,
    fill=True,
    color="yellow",
)
ax.add_patch(background_geometry)

inset_axes = inset_axes(
    ax, width=1, height=1, bbox_transform=ax.transData, bbox_to_anchor=(0, 0.55), loc=3
)

plt.show()

我知道我可以将它设置为一个小的负值来对此进行调整,但我想了解这是从哪里来的以及如何正确解决问题。 我也尝试了各种想法,包括紧凑的布局和边距,但 none 的工作。

您使用的 inset_axes locator 有一个 borderpad 参数,默认为 0.5,相当于填充 5 个点。只需将其设置为零即可对齐两个轴对象:

....    
in_ax = inset_axes(
    ax, width=1, height=1, bbox_transform=ax.transAxes, bbox_to_anchor=(0, 0.55), loc=3, 
    borderpad=0
)
....

输出:

你也不应该用你的新轴对象覆盖 matplotlib inset_axes 方法,以防你想创建第二个插图。