Skip to content

Commit e64af6d

Browse files
sramesh750tacaswell
authored andcommitted
FIX: savefig(...,transparent=True) now makes inset_axes transparent
1 parent 647afe6 commit e64af6d

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

lib/matplotlib/figure.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3061,10 +3061,24 @@ def savefig(self, fname, *, transparent=None, **kwargs):
30613061
if transparent:
30623062
kwargs.setdefault('facecolor', 'none')
30633063
kwargs.setdefault('edgecolor', 'none')
3064+
# set subfigure to appear transparent in printed image
3065+
for subfig in self.subfigs:
3066+
stack.enter_context(
3067+
subfig.patch._cm_set(
3068+
facecolor='none', edgecolor='none'))
3069+
for subfig_ax in subfig.axes:
3070+
stack.enter_context(
3071+
subfig_ax.patch._cm_set(
3072+
facecolor='none', edgecolor='none'))
3073+
# set axes to be transparent
30643074
for ax in self.axes:
30653075
stack.enter_context(
30663076
ax.patch._cm_set(facecolor='none', edgecolor='none'))
3067-
3077+
# set inset axes to be transparent as well
3078+
for child_ax in ax.child_axes:
3079+
stack.enter_context(
3080+
child_ax.patch._cm_set(
3081+
facecolor='none', edgecolor='none'))
30683082
self.canvas.print_figure(fname, **kwargs)
30693083

30703084
def ginput(self, n=1, timeout=30, show_clicks=True,

lib/matplotlib/tests/test_figure.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,24 @@ def test_savefig_pixel_ratio(backend):
557557
assert ratio1 == ratio2
558558

559559

560+
@image_comparison(['transparent_background'],
561+
extensions=['png'], savefig_kwarg={'transparent': True},
562+
remove_text=True)
563+
def test_savefig_transparent():
564+
# create two transparent subfigures with corresponding transparent inset
565+
# axes. the entire background of the image should be transparent.
566+
fig = plt.gcf()
567+
gs = fig.add_gridspec(3, 3)
568+
fig.add_subfigure(gs[0, 0])
569+
fig.add_subplot(gs[0, 0])
570+
ax = plt.gca()
571+
ax.inset_axes([.1, .2, .3, .4])
572+
fig.add_subfigure(gs[0:2, 1])
573+
fig.add_subplot(gs[0:2, 1])
574+
ax2 = plt.gca()
575+
ax2.inset_axes([.1, .2, .3, .4])
576+
577+
560578
def test_figure_repr():
561579
fig = plt.figure(figsize=(10, 20), dpi=10)
562580
assert repr(fig) == "<Figure size 100x200 with 0 Axes>"

0 commit comments

Comments
 (0)