【发布时间】: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 上正常工作吗?
【问题讨论】:
-
我已经查看了上述问题/答案,并尝试添加
plt.ioff()。现在,如果%matplotlib widget在 JN 单元格上执行,则只会显示一张图片。如果%matplotlib widget未执行,则输出单元格上不会显示任何图片:我在 OP 中提到的 UserWarning 被引发。我还注意到,通过在__init__中实例化图形,我的 sphinx 文档随机插入了两次相同的图。我讨厌 matplotlib :( 我可能必须重构类和测试,以便仅在调用show()时实例化图形。
标签: python matplotlib jupyter-notebook matplotlib-widget