Matplotlib savefig 背景总是透明的

Ric*_*ard 3 python matplotlib python-3.x

问题

我似乎无法savefig()在没有透明图形背景的情况下实际保存 PNG 文件。

这是阅读并尝试了之前发布的所有建议,回答,诅咒以及多次浏览 API 文档。我已经阅读了所有内容,但仍然无法获得不透明的人脸

背景

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

然而,我正在 jupyter 中尝试这个 - 所以希望它不是完全搞砸了,只有 jupyter 中的 ipython 是如何做到的 - 尽管我不明白这是怎么回事

我确实阅读了之前的许多关于 savefig 用背景做自己的事情的(令人困惑的)性质的文章,并按照建议(以及最新的 savefig api 文档中所写的)做了/尝试了所有事情。

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

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

当保存我的图背景总是透明的


谁能告诉我 !@#$!# 我在这里失踪了???

代码

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

特别是下面的第二个调用(使用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)
Run Code Online (Sandbox Code Playgroud)

EA3*_*4GT 7

不幸的是,frameon从 matplotlib 3.3 开始,它似乎不再受支持。

我通过设置facecolor='white', transparent=False选项解决了透明度问题savefig()

  • 只需 `facecolor='white'` 就足够了。 (7认同)