Python 如何从具有透明背景的 matplotlib 导出图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15857647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:11:19  来源:igfitidea点击:

How to export plots from matplotlib with transparent background?

pythonmatplotlibplottransparency

提问by Cupitor

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

我正在使用 matplotlib 制作一些图形,不幸的是我无法在没有白色背景的情况下导出它们。

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?

换句话说,当我像这样导出一个图并将其放置在另一个图像的顶部时,白色背景隐藏了它后面的内容而不是让它显示出来。如何导出具有透明背景的绘图?

采纳答案by Warren Weckesser

Use the matplotlib savefigfunction with the keyword argument transparent=Trueto save the image as a png file.

使用savefig带有关键字参数的 matplotlib函数transparent=True将图像保存为 png 文件。

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

结果: 演示.png

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

当然,那个情节并没有表现出透明度。这是使用 ImageMagickdisplay命令显示的 PNG 文件的屏幕截图。棋盘格图案是通过 PNG 文件的透明部分可见的背景。

display screenshot

显示截图

回答by Stephane Rolland

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

Png 文件可以处理透明度。因此,您可以使用此问题Save plot to image file 而不是使用 Matplotlib 显示它,以便将图形保存为png文件。

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

如果你想把所有白色像素都变成透明,还有另一个问题:使用 PIL 使所有白色像素透明?

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.

如果你想把整个区域变成透明,那么有这个问题:然后像在这个问题中使用 PIL 库Python PIL: how to make area transparent in PNG? 以使您的图形透明。