A previous question dealt with using savefig()
to save with the same facecolor (background color) as is displayed on screen, namely:
fig = plt.figure()
fig.patch.set_facecolor('blue')
fig.savefig('foo.png', facecolor=fig.get_facecolor())
Matplotlib figure facecolor (background color)
(Using savefig()
requires us to respecify the background color.)
I can also specify an alpha for transparency, e.g.: How to set opacity of background colour of graph wit Matplotlib
fig.patch.set_alpha(0.5)
I can't find a way to make the figure with a transparent facecolor save as it appears onscreen. The documentation seems incomplete on this: http://matplotlib.org/faq/howto_faq.html#save-transparent-figures - the actual saving isn't showing. Using transparent=True
with savefig()
does not have the desired effect of making the facecolor transparent, instead it seems to make everything except axes legend transparent on top of that color (including graph backgrounds).
EDIT: Some relevant extracts of code:
def set_face_color(fig, facecolor):
if facecolor is False:
# Not all graphs get color-coding
facecolor = fig.get_facecolor()
alpha = 1
else:
alpha = 0.5
color_with_alpha = colorConverter.to_rgba(
facecolor, alpha)
fig.patch.set_facecolor(color_with_alpha)
def save_and_show(plt, fig, save, disp_on, save_as):
if save:
plt.savefig(save_as, dpi=dpi_file, facecolor=fig.get_facecolor(),
edgecolor='none')
if disp_on is True:
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.show()
else:
plt.close('all')
It might be possible to combine these, but I often call set_face_color()
at the beginning of a graphing function before I build up a grid of subplots and then save_and_show()
toward the end. I guess it should work in either place, but optimally I'd prefer to keep the functions separate and be able to extract the alpha to pass to savefig()
from the final fig.
EDIT 2 - Worth a thousand words
Alpha = 0.5 on the left, 1 on the right.
t = [1, 2, 3, 4, 5]
fig = plt.figure()
fig.patch.set_alpha(0.5)
fig.set_facecolor('b')
plt.plot(t, t)
fig2 = plt.figure()
fig2.set_facecolor('b')
plt.plot(t,t)