【问题标题】:How do you save Matplotlib figure with an opaque white border?如何用不透明的白色边框保存 Matplotlib 图形?
【发布时间】:2018-09-21 21:38:59
【问题描述】:

从 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'

【问题讨论】:

    标签: python matplotlib plot jupyter-notebook transparency


    【解决方案1】:

    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')
    

    事实证明这是特定于 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
    )
    

    【讨论】:

      猜你喜欢
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2014-08-23
      • 1970-01-01
      • 2019-02-21
      • 2020-11-29
      • 1970-01-01
      相关资源
      最近更新 更多