oliversm
oliversm

Reputation: 1967

Matplotlib - savefig ignores facecolor when saving with transparency

I was surprised to find that when I use savefig with transparent=True this removed the facecolor which I might have set.

How can I not lose any background colours I manually set (including white)?

Compare

The GUI

enter image description here

Using transparent=False

plt.savefig('temp.pdf', format='pdf', transparent=False, bbox_inches='tight')

enter image description here

Using transparent=True

plt.savefig('temp.pdf', format='pdf', transparent=True, bbox_inches='tight')

enter image description here

MWE

import matplotlib as mpl

rc_fonts = {
    "text.usetex": True,
    'text.latex.preview': True,
    "font.size": 50,
    'mathtext.default': 'regular',
    'axes.titlesize': 55,
    "axes.labelsize": 55,
    "legend.fontsize": 50,
    "xtick.labelsize": 50,
    "ytick.labelsize": 50,
    'figure.titlesize': 55,
    'figure.figsize': (10, 6.5),  # 15, 9.3
    'text.latex.preamble': [
        r"""\usepackage{lmodern,amsmath,amssymb,bm,physics,mathtools,nicefrac,letltxmacro,fixcmex}
        """],
    "font.family": "serif",
    "font.serif": "computer modern roman",
}
mpl.rcParams.update(rc_fonts)
import matplotlib.pylab as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, InsetPosition, mark_inset
from numpy import linspace, sin


x = linspace(0, 1, 100)
plt.clf()
ax1 = plt.gca()
ax2 = plt.axes([0, 0, 1, 1], label=str(2))
ip = InsetPosition(ax1, [0.08, 0.63, 0.45, 0.3])
ax2.set_axes_locator(ip)
ax1.plot(x, x)
ax1.plot(x, x + 0.3)
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
plt.setp(ax2.get_xticklabels(), backgroundcolor="white")
ax2.set_facecolor('grey')
ax1.set_yticks([])
ax1.set_xticks([])
ax2.set_yticks([])
ax1.text(0.3, 0.3, '$1$', transform=ax1.transAxes, horizontalalignment='center', verticalalignment='center', color='black', backgroundcolor='white')

Desired output

I would like it so that any background colurs default to None (or similar), such that if it is unspecified, then it will be transparent, and if it is specified, then it will be respected and opaque. Hence I would like the following output (using a blue background for added clarity):

What I would like:

enter image description here

Currently if I use facecolor=(1,1,1,0) it correctly removes all the colours around the margins, but the main plot area is still white.

Upvotes: 4

Views: 3044

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339300

It looks like you can achive the desired output via

ax1.set_facecolor((1,1,1,0))
ax2.set_facecolor("grey")
fig.savefig(__file__+".pdf", facecolor=(1,1,1,0))

Upvotes: 5

Related Questions