Matplotlib: How to plot in main axis on top of insets with colors (do not make insets transparent)

Viewed 502

I am trying to make the lines plotted in the main axes appear on top of the insets. It seems to me that the mpl_toolkits.axes_grid1.inset_locator.inset_axes(..., axes_kwargs={"zorder": 5}) only controls the z-order between multiple insets, but does not control the z-order between the insets and the other artists, such as ax.plot(..., zorder=10). In this case, the inset_axes would still appear on top of ax.plot, despite the ax.plot having a larger z-order.

Right now with the code below, I am producing the plot below. I want the blue and red sinusoids in the main axis to appear on top of the insets.

Edit: If one is okay with making the insets transparent/default white color, then @swatchai's answer of axins.set_facecolor("none") is adequate. However, I am sorry that means I need to update my minimal example - I actually also need to keep the opaque colors of the insets as well.

enter image description here

"""
Modified based on: https://matplotlib.org/3.1.1/gallery/axes_grid1/inset_locator_demo.html
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from numpy import linspace, sin, cos, pi

fig, ax = plt.subplots(1, 1, figsize=[6, 6])

# Create inset of width=3.0, height=3.0 inches
# at the default upper right location
axins = inset_axes(ax, width=3.0, height=3.0, axes_kwargs={"zorder": 3, "alpha": 0})
axins.patch.set_color("green")
axins.text(0, 0, "axins - how to put this \nbehind the cosine? \nAlso please keep this background green"); axins.set_xlim([-0.5, 1])

# Create inset of width="50%", height="50%" of the parent axes' bounding box
# at the lower left corner (loc=3)
axins2 = inset_axes(ax, width="50%", height="50%", axes_kwargs={"zorder": 5}, loc=3); axins2.patch.set_zorder(5)
# patch.set_zorder seems to have the same effect as axes_kwargs
axins2.set_facecolor("yellow")
axins2.text(0, 0, "axins2\nhow to put this also behind the cosine? \nAlso please keep this background yellow")

# Plot sine in main axis - please bring these lines on top of the two insets
ax.plot(linspace(0, 1), cos(linspace(0, 1) * 10 * pi), c='b', zorder=10)
ax.plot(linspace(0, 1), sin(linspace(0, 1) * 10 * pi), c='r', zorder=4)

plt.show()
1 Answers

You need to set axes' facecolor to "none" in both inset_axes.

axins.set_facecolor("none")
axins2.set_facecolor("none")

And you will get a plot like this:

enter image description here

Edit 1

Using semi-transparent background color will get to half-way of what you want.

axins.set_facecolor('#0fff0f60')
axins2.set_facecolor('#ffff0f60')

Output plot:

plot_2

Related