Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 764
N8_Coder Avatar asked Apr 13 '26 22:04

N8_Coder


1 Answers

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.

like image 148
Mr. T Avatar answered Apr 15 '26 11:04

Mr. T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!