标签归档:transparency

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

问题:如何从具有透明背景的matplotlib中导出图?

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

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

I am using matplotlib to make some graphs and unfortunately I cannot export them without the 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?


回答 0

使用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)

结果:

当然,该图没有显示出透明度。这是使用ImageMagick display命令显示的PNG文件的屏幕截图。棋盘图案是通过PNG文件的透明部分可见的背景。

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:

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.


回答 1

Png文件可以处理透明度。因此,您可以使用此问题将图保存到图像文件中,而不是使用Matplotlib显示它,以便将图形另存为png文件。

如果要使所有白色像素透明,则还有另一个问题:使用PIL使所有白色像素透明吗?

如果您想将整个区域变成透明,那么会有一个问题:然后像这个问题一样使用PIL库Python PIL:如何在PNG中使区域透明?以使您的图表透明。

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.