你如何用不透明的白色边框保存Matplotlib图?

时间:2018-04-11 21:17:06

标签: python matplotlib plot jupyter-notebook transparency

从Jupyter笔记本中保存Matplotlib图时,如何覆盖默认的透明边框,使其不透明?

查看savefig documentation,有几个参数似乎会影响这个但实际上似乎没有做任何事情。这是一个例子。

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = np.linspace(-6, 6, 100)
ax.plot(x, np.sinc(x))
plt.savefig(
    'test.png', 
    transparent=False, # no change
    frameon=True, # no change
    edgecolor='blue', # no change (want 'white' but 'blue' should be noticeable)
    facecolor='red', # no change (want 'white' but 'red' should be noticeable)
    alpha=1, # no change
)

结果如下。 StackOverflow没有说明透明度,但请注意边缘不是'blue'而且脸部不是'red'

result

1 个答案:

答案 0 :(得分:0)

This post提到设置fig.patch.set_alpha(1),无论savefig参数如何,都会生效。将此命令添加到示例代码可以解决问题。

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fig.patch.set_alpha(1)  # solution

x = np.linspace(-6, 6, 100)
ax.plot(x, np.sinc(x))
fig.savefig('solved.png')

enter image description here

事实证明这是特定于Jupyter笔记本,并且可能是一个错误(我只有4.4.0版本)。当我从命令行运行上面的代码时,我得到了所需的行为(将'red'更改为'white'以获得不透明的白色边框。)

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = np.linspace(-6, 6, 100)
ax.plot(x, np.sinc(x))
plt.savefig(
    'test.png', 
    # transparent=False, # no change
    # frameon=True, # no change
    # edgecolor='blue', # no change
    facecolor='red', # no change
    # alpha=1, # no change
)

red