Matplotlib的savefig背景总是透明的。

29

问题

我似乎无法使用savefig()保存PNG文件,而不带有透明的图形背景。

我已经阅读并尝试了以前发布、回答和诅咒过的所有建议,并多次查看了API文档。我已经阅读了所有相关内容,但仍然无法获得非透明的图形面板。

背景

我正在使用matplotlib和savefig创建PNG文件(环境:macos - 最新anaconda模块使用PY 3.7)。

我正在尝试在jupyter中执行此操作-因此希望这不是只有ipython在jupyter中才会出现的问题-尽管我不知道可能性有多大。

我确实阅读了以前关于savefig(与背景进行自己处理的鬼畜)性质的许多帖子,并尝试了建议的每一项(以及在最新的savefig api文档中编写的每一项)。

特别是,我已经尝试了以下所有方法但都没有成功:

  • 在savefig()调用中指定facecolor(具有/不具有透明度)
  • 在我正在使用的mpl文件中使用savefig.facecolor: white样式

savefig我的图形背景总是透明的


有人可以告诉我我错过了什么吗???

代码

这是我正在使用的内容,它会输出具有透明背景的图形,无论我做什么。

特别是下面的第二个调用(带有savefig(..., transparent=False))将使轴不透明-但图形本身仍然是透明的!

import numpy as np
import matplotlib as mpl
import matplotlib.style as style

a = np.array([-3.2, 0.1, 1.5, 3.3, 8.5])
b = np.array([1.1, 1.8, 1.95, 2.3, 4.3])
labels = ['a', 'bc', 'def', 'g', 'ggghhh']

stylefile = './util/plot_config/aqs_default.mplstyle'
# the file above does contain an entry of:
# savefig.facecolor: white
#
to_res = 1024
dpi = 100
inches = (to_res/dpi, to_res/dpi)

style.use(stylefile)
%matplotlib   

fig = mpl.figure.Figure(figsize=inches, dpi=dpi, facecolor='white')
ax = fig.subplots()

for x, y, l in zip(a,b,labels):
    ax.scatter(x,y,label=l)
ax.legend()
ax.set_xlabel('Some x')
ax.set_ylabel('Attenuation $\mu$ (cm$^{-1}$)')

ax.set_title('blah', y=1.03)
fig.suptitle('Linearity $\mu$')

# for me, _both_ calls below result in the figure having a transparent background:

fig.savefig('a.png', facecolor=fig.get_facecolor(), transparent=True)
fig.savefig('b.png', facecolor=fig.get_facecolor(), transparent=False)

你遇到了什么错误?你尝试使用绝对路径了吗? - Arun Kamalanathan
fig.get_facecolor() 打印什么? - ImportanceOfBeingErnest
1
我想知道在你的情况下 print(fig.get_facecolor()) 在屏幕上显示什么。最好将该行代码合并到你的代码中,并在问题中报告结果。 - ImportanceOfBeingErnest
...奇怪的是你无法复现!...但还是感谢你的尝试。 - Richard
抱歉耽搁了!我在使用mpl创建fig和ax时,无论是通过mpl还是pyplot,都会得到“MacOSX MacOSX white”。然而,仍然存在这样一种情况,即仅通过mpl创建时始终会给我透明的背景,但是通过plt创建则不会。...很奇怪。无论如何 - 非常感谢您尝试挖掘它! - Richard
显示剩余8条评论
2个回答

49
很遗憾,自matplotlib 3.3版本以来,似乎不再支持frameon选项。
我通过在savefig()中设置选项facecolor='white', transparent=False解决了透明度问题。

谢谢,这个很好用!我在使用savefig保存seaborn生成的图时遇到了这个问题。 - Cornelius Roemer
7
只需添加 facecolor='white' 即可。 - Denziloe
这个回答应该有更多的赞和被接受为答案。谢谢! - bmasri

4

提供给遇到类似问题的人参考。

问题的原因(以及解决方案)是因为我创建了一个带有frameon属性设置为False的图形。实际上,我在使用的样式文件中已经将其设置为False了。

frameon改为True可以解决问题。

这个问题并不明显,也没有任何文档说明,以下是MPL Github问题背景介绍: https://github.com/matplotlib/matplotlib/issues/14339


2
savefig() got unexpected keyword argument "frameon" which is no longer supported as of 3.3 and will become an error two minor releases later - EA304GT
请查看下面的答案,该答案已更新为版本3.3及更高版本的正确答案。 - Richard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接