Can someone please explain why the code below does not work when setting the facecolor of the figure?
import matplotlib.pyplot as plt
# create figure instance
fig1 = plt.figure(1)
rect = fig1.patch
rect.set_facecolor('red') # works with plt.show().
# Does not work with plt.savefig("trial_fig.png")
ax = fig1.add_subplot(1,1,1)
x = 1, 2, 3
y = 1, 4, 9
# plt.show() # Will show red face color set above using rect.set_facecolor('red')
plt.savefig("trial_fig.png") # The saved trial_fig.png DOES NOT have the red facecolor.
# plt.savefig("trial_fig.png", facecolor='red') # Here the facecolor is red.
savefig overrides the facecolor for the background of the figure.
(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the
facecolor kwarg to
savefig. It's a confusing and inconsistent default, though!)
The easiest workaround is just to do
fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none') (I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)
Hope that helps!