Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: enter image description here

Also see How to overlay plots from different cells?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...