Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I show the same matplotlib figure several times in a single IPython notebook?

I use IPython notebooks with matplotlib.pyplot and I often create a plot that requires a fairly large block of code to generate. I would then like to save the object and use that exact same figure/axes pair to incorporate in another plot later on.

For example, suppose I have some pairs of x-y data for a scatter plot. I'd like to show the points and then several cells later--potentially with other calls to pyplot to make other, unrelated figures--I would like to show that figure again so that I could plot over it with a regression line or some other graphics.

In the picture I've attached below, I have a short notebook; I want the figure from cell #2 to be drawn in cell #3 without calling pyplot.scatter again.

Essentially, I want to show the figure again without repeating all the code. What are my options for doing this? I have been unable to accomplish this with calls to show() or draw() or by setting the current figure object in the cell to be my saved figure object. Any advice is welcome. Thanks!

P.S. I know that if I reuse the figure and plot over it, the object will change and so the state of the fig object may not match the plot that was drawn in a previous IPython cell. That's okay for my work.

Example IPython notebook

like image 961
Christopher Krapu Avatar asked Mar 28 '16 15:03

Christopher Krapu


2 Answers

Just call myFigure in any cell after myFigure was assigned in cell before.

For example in cell 1:

In [1]:
myFigure, myAx = plt.subplots()
myAx.plot([1,2,3])

In cell after that:

In [2]:
myFigure

This will show myFigure

like image 121
Primer Avatar answered Sep 25 '22 20:09

Primer


Assuming that you're using the default matplotlib backend (%matplotlib inline) in Jupyter Notebook.

Then, to show a plot in the notebook, you have to display the figure. There are 3 ways to do that.

  1. Any just-created non-closed plots (see also this answer for how to close the plot) will be automatically displayed when the cell finishes running. This happened when you run the first cell.

  2. Put fig (a matplotlib.figure.Figure instance) at the end of any cell.

    This method is already mentioned in the other existing answer, but note that it must be at the last line, and must not have a trailing ;. (this is the same for every object types. If you execute a cell with content 1 it will show 1 in the output, but 1; will not show anything)

  3. Use IPython.display.display(fig).

Note that print(fig) will not work, because this will only send a string representation of the figure to sys.stdout (so something like <Figure> is displayed in the notebook).

like image 45
user202729 Avatar answered Sep 25 '22 20:09

user202729