1
votes

I'd like to save a figure with a transparent background where the tick marks and axis labels are transparent but the subplot faces are colored. I can accomplish the transparent background using savefig with transparent=True, and the latter by setting facecolor='red' for each axis within the subplots, but canno get both to work at the same time.

I include a MWE in which the plt.show() will create the desired facecolors, while the saved transparent fig is shown on a keynote slide. Thanks for your help!

import os.path as op
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(10)
y0 = np.random.rand(50)
y1 = np.random.rand(50)
x  = range(len(y1))

fig, (axe0, axe1) = plt.subplots(nrows=2, sharex=True)
axe0.scatter(x, y0, c='k')
axe0.set_facecolor('red')
axe1.scatter(x, y1, c='k')
axe1.set_facecolor('blue')
dst = op.join(op.expanduser('~'), 'Desktop', 'Temp.png')
fig.savefig(dst, transparent=True, format='png')
plt.show()

Correct colored subplots

Transparent on slide

1

1 Answers

0
votes

Dont set transparent true, but set opacity=0 by using

fig.patch.set_alpha(0.0)

I have modified your code as below:

fig, (axe0, axe1) = plt.subplots(nrows=2, sharex=True)
axe0.scatter(x, y0, c='k')
axe0.set_facecolor('red')
axe1.scatter(x, y1, c='k')
axe1.set_facecolor('blue')
dst = op.join(op.expanduser('~'), 'Desktop', 'Temp.png')
fig.patch.set_alpha(0.0)
fig.savefig(dst, format='png')
plt.show()