The Python Oracle

How to export plots from matplotlib with transparent background?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop

--

Chapters
00:00 How To Export Plots From Matplotlib With Transparent Background?
00:28 Accepted Answer Score 288
01:07 Answer 2 Score 5
01:24 Thank you

--

Full question
https://stackoverflow.com/questions/1585...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib #plot #transparency

#avk47



ACCEPTED ANSWER

Score 288


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




ANSWER 2

Score 5


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()