How to set opacity of background colour of graph with Matplotlib
Solution 1:
If you just want the entire background for both the figure and the axes to be transparent, you can simply specify transparent=True
when saving the figure with fig.savefig
.
e.g.:
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', transparent=True)
If you want more fine-grained control, you can simply set the facecolor and/or alpha values for the figure and axes background patch. (To make a patch completely transparent, we can either set the alpha to 0, or set the facecolor to 'none'
(as a string, not the object None
!))
e.g.:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.patch.set_facecolor('blue')
fig.patch.set_alpha(0.7)
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.patch.set_facecolor('red')
ax.patch.set_alpha(0.5)
# If we don't specify the edgecolor and facecolor for the figure when
# saving with savefig, it will override the value we set earlier!
fig.savefig('temp.png', facecolor=fig.get_facecolor(), edgecolor='none')
plt.show()
Solution 2:
Another way is to set the appropriate global rcParams
and simply specify the colors. Here is an MWE (I used the RGBA color format to specify the alpha/opacity):
import matplotlib.pyplot as plt
plt.rcParams.update({
"figure.facecolor": (1.0, 0.0, 0.0, 0.3), # red with alpha = 30%
"axes.facecolor": (0.0, 1.0, 0.0, 0.5), # green with alpha = 50%
"savefig.facecolor": (0.0, 0.0, 1.0, 0.2), # blue with alpha = 20%
})
plt.plot(range(10))
plt.savefig("temp.png")
plt.show()
The figure.facecolor
is the main background color and the axes.facecolor
the background color of the actual plot. For whatever reason, plt.savefig
uses savefig.facecolor
as the main background color rather than figure.facecolor
, so make sure to change this parameter accordingly.
plt.show()
from the code above results in the following output:
and plt.savefig("temp.png")
results in this output:
If you want to make something completely transparent, simply set the alpha value of the corresponding color to 0. For plt.savefig
, there is also a "lazy" option by setting the rc-parameter savefig.transparent
to True
, which sets the alpha of all facecolors to 0%.
Note that altering the rcParams
has a global effect, so bear in mind that all your plots will be affected by these changes. However, this solution can be extremely useful if you have multiple plots, or if you want to change the appearance of plots where you cannot change the source code.