问题
我似乎无法使用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)
fig.get_facecolor()
打印什么? - ImportanceOfBeingErnestprint(fig.get_facecolor())
在屏幕上显示什么。最好将该行代码合并到你的代码中,并在问题中报告结果。 - ImportanceOfBeingErnest