Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export plots from matplotlib with transparent background?

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?

like image 793
Cupitor Avatar asked Oct 17 '22 06:10

Cupitor


People also ask

How do I make the background transparent in matplotlib?

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%.

How do I save a matplotlib plot without white space?

To removing white space around a saved image with Python matplotlib, we call plt. savefig with the bbox_inches argument set to 'tight' . to call savefig to save the flots to myfile. png.

How do you change the background of a plot in matplotlib?

Matplotlib change background color inner and outer colorset_facecolor() method is used to change the inner background color of the plot. figure(facecolor='color') method is used to change the outer background color of the plot.

Which function can be used to export generate graph in matplotlib to PNG?

Syntax of savefig() function fname : path or name of output file with extension. If extension is not provided plot is saved as png file.


2 Answers

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

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

like image 252
Warren Weckesser Avatar answered Oct 18 '22 18:10

Warren Weckesser


Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

like image 4
Stephane Rolland Avatar answered Oct 18 '22 19:10

Stephane Rolland