如何从具有透明背景的matplotlib中导出图? [英] How to export plots from matplotlib with transparent background?

查看:223
本文介绍了如何从具有透明背景的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?

推荐答案

使用带有关键字参数transparent=True的matplotlib savefig函数将图像另存为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)

结果:

当然,该图不显示透明度.这是使用ImageMagick display命令显示的PNG文件的屏幕截图.棋盘图案是通过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.

这篇关于如何从具有透明背景的matplotlib中导出图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆