如何向多个单元格中的图形添加绘图命令,但只在最后显示它? [英] How to add plot commands to a figure in more than one cell, but display it only in the end?

查看:13
本文介绍了如何向多个单元格中的图形添加绘图命令,但只在最后显示它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Jupyter Notebook 中执行以下操作:

I want to do the following in a Jupyter Notebook:

  • 在单元格中创建一个pyplot.figure
  • 对于每个后续单元格,计算值并将它们绘制成相同的图形而不显示任何内容;
  • 最后,在另一个单元格中,显示带有每个先前绘图命令结果的图形.

目前,在使用 %matplotlib notebook 时,图形总是在创建它的同一个单元格之后显示,我什至不调用 plt.show().

Currently, while using %matplotlib notebook, the figure is always displayed after the same cell it's been created, and I don't even call plt.show().

这不是我想要的行为.相反,我只想推迟最后一个单元格的图形显示,但图形当然应该包含在其间的单元格中调用的顺序绘图命令的结果.

This is not the behavior I desire. Instead I would like to postpone the display of the figure for the last cell only, but the figure of course should contain the results of the sequential plot commands called in the cells in between.

推荐答案

您可以使用魔术命令 %%capture 捕获 jupyter notebook 单元格的内容.您还可以通过在其末尾放置 ; 来隐藏特定行的任何输出.

You can capture the content of a cell of a jupyter notebook using the magic command %%capture. You can also hide any output of a specific line by putting a ; at the end of it.

只需键入存储图形的变量即可显示图形,例如fig.

Showing the figure can be done by simply typing the variable in which the figure is stored, e.g. fig.

结合这些技术给你

import matplotlib.pyplot as plt
%matplotlib notebook

%%capture captured
fig, ax=plt.subplots()

ax.plot([1,2,3]);

fig  # now show the figure

在像这样的实际笔记本中可能更容易理解:

which is probably more understandable in the acutal notebook like this:

另请参阅如何叠加来自不同单元格的图?

这篇关于如何向多个单元格中的图形添加绘图命令,但只在最后显示它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆