N8_Coder
N8_Coder

Reputation: 803

Gap between matplotlib axis and inset_axes

I want to add an inset_axis which alings with the surrounding axis. Therefore, I set the first value of the bbox_to_anchor=(0, 0.5) argument to zero. However, there is always a very small gap between their y-axes, see image:

enter image description here

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

I know I can set it to a small negative value to adjust for this, but I would like to understand where this is coming from and how to properly solve the problem. I also tried various idea including tight-layouts and margins, but none of the worked.

Upvotes: 2

Views: 771

Answers (1)

Mr. T
Mr. T

Reputation: 12410

The inset_axes locator you use has a borderpad parameter which is by default 0.5, equivalent to a padding of 5 points. Just set it to zero to align both axes objects:

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

Output:

enter image description here

You should also not overwrite the matplotlib inset_axes method with your new axis object in case you want to create a second inset.

Upvotes: 2

Related Questions