How to export plots from matplotlib with transparent background?
Asked Answered
C

2

181

I am using matplotlib to make some graphs and unfortunately I cannot export them without the white background.

sample plot with solid white background

In other words, when I export a plot like this and position it on top of another image, the white background hides what is behind it rather than allowing it to show through. How can I export plots with a transparent background instead?

Cini answered 7/4, 2013 at 0:47 Comment(0)
T
280

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [28]: import numpy as np

In [29]: from matplotlib.pyplot import plot, savefig

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

Tremblay answered 7/4, 2013 at 1:51 Comment(2)
Just for FYI for others using this. savefig is under matplotlib.pyplotGannet
Thanks @RuiNian! I added the appropriate imports to show how np, plot and savefig are imported.Tremblay
P
2

As a reminder, the plt.savefig() should be written before the plt.show(), otherwise, a transparent image will be created (without the actual plot).

For high-quality images:

plt.savefig('filename.png', format='png', dpi='600', transparent=True)
plt.show()
Pearce answered 1/11, 2022 at 7:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.