Search code examples
pythonmatplotlibzoomingtransparent

How to make the main axes transparent, while make the zoomed_inset_axes not transparent in matplolib


Currently, the figure I plot is all transparent shown as below, which makes it differentiate between zoomed part and the original part.enter image description here

Another thing is the location of the zoomed part, "loc" keyword only has 1,...9, 9 options, can I specify the location I prefer, using coordinate for example?

axins = zoomed_inset_axes(ax, 3, loc=5) # zoom = 6

I wrote a simple code your modification purpose.

from pylab import *
import re
rc('font',family='Arial')
matplotlib.rc('legend', fontsize=24)

from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
font = {'family' : 'Arial',
    'weight' : 'normal',
    'size'   : 24}
fig = figure(figsize=(8,8))
fig.set_alpha(0.0)
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x=[0,1]
y=[0,1]
plot(x,y)
axins = zoomed_inset_axes(ax, 3, loc=5) # zoom = 6

axins.plot(x,y)


# sub region of the original image
x1, x2, y1, y2 = 0.3, 0.4,  0.3,0.4
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)

plt.xticks(visible=False)
plt.yticks(visible=False)

# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=3, fc="none", ec="0.5")

plt.draw()
plt.show()
fig.savefig('1.png', transparent=True)

Below is the plot of this simple code. enter image description here


Solution

  • Just before your call to savefig, execute:

    fig.patch.set_alpha(0)
    ax.patch.set_alpha(0)
    axins.patch.set_alpha(1)
    axins.patch.set_facecolor('#909090')
    

    This will make the figure background transparent, as well as that of the main axes, but not of the zoomed axes.

    Then, make sure not to call savefig with the option transparent=True, because that will remove all backgrounds. Just set transparent=False in that call, which is also the default for savefig.