I am trying to control the color around a region between the inset axis and a certain border around it,e.g. between the blue border and the inset axis
this can be easily done for a normal axis but I can't figure out how to do it for an inset axis, what I do is like here, same as this example but for an inset axis.
As per this GitHub issue, the inset axes do not have a background that can be changed (they're just an Axes
object). What is recommended there is to create a patch the size of the axes using ax.get_tightbbox
and place it behind the inset axes.
Update: Inspired by @Redox's answer posted shortly after mine, I've added a border variable to my example and the forgotten zorder
so that the plot lines are behind the patch.
Here is a short example of how that can be done.
import matplotlib.pyplot as plt
plt.close("all")
fig, ax = plt.subplots(figsize=[5.5, 2.8])
axins = ax.inset_axes([0.2, 0.4, 0.4, 0.5])
x = [0, 2]
y = [0, 2]
ax.plot(x, y)
axins.plot(x, y)
coords = ax.transAxes.inverted().transform(axins.get_tightbbox())
border = 0.02
w, h = coords[1] - coords[0] + 2*border
ax.add_patch(plt.Rectangle(coords[0]-border, w, h, fc="green",
transform=ax.transAxes, zorder=2))
fig.show()