为什么 savefig 和 plot 命令必须在 IPython 笔记本中的同一个单元格中?

Why does savefig and plot commands have to be in the same cell in an IPython notebook?

我试图从 IPython 笔记本中导出一些图表。搜索我发现 this question 并且可以解决问题。正如答案中所指出的,我不得不在与 plot 命令相同的单元格中调用 savefig

我的问题是,为什么这些调用必须在同一个单元格中?我的笔记本服务器以 [​​=13=] 模式启动。如果它不是内联的,绘图就可以很好地导出。

我认为您从 IPython 的代码库 part 中看到了行为:

def show(close=None):
    """Show all figures as SVG/PNG payloads sent to the IPython clients.
    Parameters
    ----------
    close : bool, optional
      If true, a ``plt.close('all')`` call is automatically issued after
      sending all the figures. If this is set, the figures will entirely
      removed from the internal list of figures.
    """
    if close is None:
        close = InlineBackend.instance().close_figures
    try:
        for figure_manager in Gcf.get_all_fig_managers():
            display(figure_manager.canvas.figure)
    finally:
        show._to_draw = []
        # only call close('all') if any to close
        # close triggers gc.collect, which can be slow
        if close and Gcf.get_all_fig_managers():
            matplotlib.pyplot.close('all')

显示打开的图形后,所有打开的图都被关闭。

发生这种情况是因为默认情况下,IPython Notebook 中使用的内联后端将在每个单元格为 运行 后自动关闭所有 matplotlib 图形。您可以通过 IPython.display.set_matplotlib_close 更改此行为,如 here.

所述