【发布时间】:2020-03-30 22:50:28
【问题描述】:
问题
我似乎无法让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)
【问题讨论】:
-
您遇到什么错误?你试过绝对路径吗
-
我没有收到任何错误 - 代码中没有任何错误。问题是我的输出 PNG 文件 总是 有一个透明的图形背景,不管我做了什么其他事情(让它变白)
-
fig.get_facecolor()打印什么? -
fig.get_facecolor() 返回为图形的 facecolor 设置的颜色(当我声明 fig 大约 10 行时设置)。 ...它不打印任何东西。所以这里告诉 fig.savefig 使用 fig 对象的 facecolor,但查询 fig 以找出它的 facecolor 设置。
-
我想知道
print(fig.get_facecolor())在您的情况下在屏幕上显示的内容。最好在代码中包含该行并报告问题中的结果。
标签: python python-3.x matplotlib