How to add plot commands to a figure in more than one cell, but display it only in the end?

℡╲_俬逩灬. 提交于 2019-12-18 07:32:19

问题


I want to do the following in a Jupyter Notebook:

  • Create a pyplot.figure in a cell;
  • For each subsequent cells, calculate values and plot them to that same figure without displaying anything;
  • At the end, in another cell, display the figure with the result of every previous plot command.

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.


回答1:


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.

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

Combining those techniques gives you

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:

Also see How to overlay plots from different cells?



来源:https://stackoverflow.com/questions/44118059/how-to-add-plot-commands-to-a-figure-in-more-than-one-cell-but-display-it-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!