【问题标题】:jupyter notebook - matplotlib shows figure even without calling plt.show()jupyter notebook - matplotlib 即使不调用 plt.show() 也会显示图形
【发布时间】:2022-01-27 05:42:53
【问题描述】:

以下是我的代码的简化示例。此类背后的想法是仅在执行show 方法时显示图形。

# my_module.py
import matplotlib.pyplot as plt
import numpy as np

class Test:
    def __init__(self):
        self._fig = plt.figure()
        self.ax = self._fig.add_subplot(1, 1, 1)

    def show(self):
        x = np.linspace(0, 10, 100)
        y = np.sin(x)
        self.ax.plot(x, y)
        self._fig.tight_layout()
        self._fig.show()

当从 Python shell 或 ipython 执行代码时,它会按预期工作。但是,如果我在 Jypter Notebook 中运行它:

from my_module import Test
t = Test()

此时,屏幕上出现了一个空的图形。我不想要那个!现在,我尝试在__init__ 中插入plt.close(self._fig),但是当我运行t.show() 时,我得到UserWarning: Matplotlib is currently using module://matplotlib_inline.backend_inline, which is a non-GUI backend, so cannot show the figure.

我还尝试使用之前的编辑 plt.close(self._fig) 加载 %matplotlib widget。图片仅在调用show时显示,但它只是一个没有交互框架的图片。

另一种选择是重写类,使图形在show 方法中创建。这远非最佳,因为我需要重新调整我的测试。

还有其他方法可以让它在所有 shell 上正常工作吗?

【问题讨论】:

  • 这能回答你的问题吗? prevent plot from showing in jupyter notebook
  • 我已经查看了上述问题/答案,并尝试添加 plt.ioff()。现在,如果%matplotlib widget 在 JN 单元格上执行,则只会显示一张图片。如果%matplotlib widget 未执行,则输出单元格上不会显示任何图片:我在 OP 中提到的 UserWarning 被引发。我还注意到,通过在 __init__ 中实例化图形,我的 sphinx 文档随机插入了两次相同的图。我讨厌 matplotlib :( 我可能必须重构类和测试,以便仅在调用 show() 时实例化图形。

标签: python matplotlib jupyter-notebook matplotlib-widget


【解决方案1】:

在原帖中我犯了两个错误。

首先将图形实例化为__init__方法,然后调用show方法。在交互式环境中,一旦创建图形,它将显示在屏幕上。我们可以使用plt.ioff() 关闭该行为,但随后会发生两件事:

  1. 如果%matplotlib widget被执行,则在调用t.show()时,图形只会出现一次。
  2. 否则,调用t.show()时屏幕上不会显示任何绘图。

因此,plt.ioff() 不是有效的解决方案。相反,必须在执行 t.show() 时实例化该图窗。

我犯的第二个错误是使用self._fig.show()。请记住,在交互式环境中,图形一经实例化就会显示出来。然后,前面的命令再次显示该图!相反,我必须使用plt.show(),它只显示一次图形。

这是正确的代码示例:

import matplotlib.pyplot as plt
import numpy as np

class Test:
    def __init__(self):
        # init some attributes
        pass

    def show(self):
        self._fig = plt.figure()
        self.ax = self._fig.add_subplot(1, 1, 1)
        x = np.linspace(0, 10, 100)
        y = np.sin(x)
        self.ax.plot(x, y)
        self._fig.tight_layout()
        plt.show()

t = Test()  # no figure is shown
t.show()    # figure is shown

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 2017-05-11
    • 1970-01-01
    • 2019-04-26
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    相关资源
    最近更新 更多