139

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)
fig1.set_figheight(11)
fig1.set_figwidth(8.5)

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
ax.plot(x, y)

# 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.

When I specify the height and width of the figure using fig1.set_figheight(11) fig1.set_figwidth(8.5) these are picked up by the command plt.savefig("trial_fig.png"). However, the facecolor setting is not picked up. Why?

Thanks for your help.

Curious2learn
  • 31,692
  • 43
  • 108
  • 125

4 Answers4

192

It's because 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)

starball
  • 20,030
  • 7
  • 43
  • 238
Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • `facecolor` now triggers a warning: `MatplotlibDeprecationWarning: savefig() got unexpected keyword argument "fc" which is no longer supported as of 3.3 and will become an error in 3.6`. – C-3PO Dec 03 '22 at 23:32
49

savefig has its own parameter for facecolor. I think an even easier way than the accepted answer is to set them globally just once, instead of putting facecolor=fig.get_facecolor() every time:

plt.rcParams['axes.facecolor']='red'
plt.rcParams['savefig.facecolor']='red'
tozCSS
  • 5,487
  • 2
  • 34
  • 31
44

I had to use the transparent keyword to get the color I chose with my initial

fig=figure(facecolor='black')

like this:

savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True)
Labibah
  • 5,371
  • 6
  • 25
  • 23
-1

Just adding the facecolor='red' to the plt.savefig() is sufficient. For example:

plt.savefig('figname.png', facecolor='red')
mOna
  • 2,341
  • 9
  • 36
  • 60