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.
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.
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.
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
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.
I hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With