Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jupyter: Replot in different cell

I'd like to do something like this:

import matplotlib.pyplot as plt
%matplotlib inline
fig1 = plt.figure(1)
plt.plot([1,2,3],[5,2,4])
plt.show()

In one cell, and then redraw the exact same plot in another cell, like so:

plt.figure(1) # attempting to reference the figure I created earlier...
# four things I've tried:
plt.show() # does nothing... :(
fig1.show() # throws warning about backend and does nothing
fig1.draw() # throws error about renderer
fig1.plot([1,2,3],[5,2,4]) # This also doesn't work (jupyter outputs some 
# text saying matplotlib.figure.Figure at 0x..., changing the backend and 
# using plot don't help with that either), but regardless in reality
# these plots have a lot going on and I'd like to recreate them 
# without running all of the same commands over again.

I've messed around with some combinations of this stuff as well but nothing works.

This question is similar to IPython: How to show the same plot in different cells? but I'm not particularly looking to update my plot, I just want to redraw it.

like image 230
aquirdturtle Avatar asked Sep 05 '16 21:09

aquirdturtle


People also ask

How do I run multiple cells in Jupyter?

First, you will need to install jupyter nbextensions configurator as described here. Then search for "Initialization cells" from inside the search bar of the Jupyter nbextension manager. A check box at the top of every cell will appear. You can select which cells to be marked as initialization cells.

How do you select specific cells in a Jupyter notebook?

Select Multiple Cells: Shift + J or Shift + Down selects the next sell in a downwards direction. You can also select sells in an upwards direction by using Shift + K or Shift + Up . Once cells are selected, you can then delete / copy / cut / paste / run them as a batch.


1 Answers

I have found a solution to do this. The trick is to create a figure with an axis fig, ax = plt.subplots() and use the axis to plot. Then we can just call fig at the end of any other cell we want to replot the figure.

import matplotlib.pyplot as plt
import numpy as np

x_1 = np.linspace(-.5,3.3,50)
y_1 = x_1**2 - 2*x_1 + 1

fig, ax  = plt.subplots()
plt.title('Reusing this figure', fontsize=20)
ax.plot(x_1, y_1)
ax.set_xlabel('x',fontsize=18)
ax.set_ylabel('y',fontsize=18, rotation=0, labelpad=10)
ax.legend(['Eq 1'])
ax.axis('equal');

This produces First plot of the figure

Now we can add more things by using the ax object:

t = np.linspace(0,2*np.pi,100)
h, a = 2, 2
k, b = 2, 3
x_2 = h + a*np.cos(t)
y_2 = k + b*np.sin(t)
ax.plot(x_2,y_2)
ax.legend(['Eq 1', 'Eq 2'])
fig

Note how I just wrote fig in the last line, making the notebook output the figure once again. Second plot of the figure!

I hope this helps!

like image 156
Romeo Valentin Avatar answered Sep 20 '22 20:09

Romeo Valentin