Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython: How to show the same plot in different cells?

I'm still new to IPython Notebooks, Jupyter, and Python in general.

I'm creating a scatter plot in a Jupyter notebook using the following code:

import numpy as np
import matplotlib.pyplot as plt

n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
plt.axes([0.025, 0.025, 0.95, 0.95])
plt.scatter(X, Y, s=50)

plt.show()

My question is, how can I get a reference to the plot object so I can use it in a different cell later on in the notebook? Additionally, I may need to modify the plot before showing it again.

Also, I have %matplotlib inline at the top of my notebook.

Here are some info about my environment:

  • Python: 3.5.2 64bit [MSC v.1900 64 bit (AMD64)]
  • IPython: 4.2.0
  • numpy: 1.11.1
  • scipy: 0.17.1
  • matplotlib: 1.5.1
  • sympy: 1.0
  • OS: Windows 7 6.1.7601 SP1
like image 725
mbadawi23 Avatar asked Aug 03 '16 21:08

mbadawi23


People also ask

How do you update a plot on the same figure during the loop?

We can use matplotlib to update a plot on every iteration during the loop. With the help of matplotlib. pyplot. draw() function we can update the plot on the same figure during the loop.


1 Answers

I have found a solution! Basically you create a figure and the axis with fig, ax = plt.subplots() and then use the ax variable to draw (potentially in multiple cells). In any of the cells you want to replot the figure, just write fig as the last line of the cell, resulting in the cell using the updated figure as output.
See my answer here for more details.

like image 200
Romeo Valentin Avatar answered Oct 23 '22 04:10

Romeo Valentin