Search code examples
pythonmatplotlibplotjupyter-notebooktransparency

How do you save Matplotlib figure with an opaque white border?


When saving a Matplotlib figure from a Jupyter notebook, how do I override the default transparent border so it will be opaque?

Looking at the savefig documentation, there are several parameters that seem like they would affect this but actually do not seem to do anything. Here is an example.

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = np.linspace(-6, 6, 100)
ax.plot(x, np.sinc(x))
plt.savefig(
    'test.png', 
    transparent=False, # no change
    frameon=True, # no change
    edgecolor='blue', # no change (want 'white' but 'blue' should be noticeable)
    facecolor='red', # no change (want 'white' but 'red' should be noticeable)
    alpha=1, # no change
)

Here is the result. StackOverflow does not illustrate the transparency, but note that the edge is not 'blue' and the face is not 'red'.

result


Solution

  • This post mentions setting fig.patch.set_alpha(1) which turns out to work, regardless of the savefig parameters. Adding this command to the example code resolves the problem.

    %matplotlib notebook
    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    fig.patch.set_alpha(1)  # solution
    
    x = np.linspace(-6, 6, 100)
    ax.plot(x, np.sinc(x))
    fig.savefig('solved.png')
    

    enter image description here

    It turns out this is specific to Jupyter notebooks, and is probably a bug (I only have version 4.4.0). When I run the following code above from the command line, I instead get the desired behavior (change 'red' to 'white' to get the opaque white border).

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    x = np.linspace(-6, 6, 100)
    ax.plot(x, np.sinc(x))
    plt.savefig(
        'test.png', 
        # transparent=False, # no change
        # frameon=True, # no change
        # edgecolor='blue', # no change
        facecolor='red', # no change
        # alpha=1, # no change
    )
    

    red