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

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

推荐答案

使用 matplotlib savefig 函数和关键字参数 transparent=True 将图像保存为 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天全站免登陆