How to reuse graph in next jupyter cell

I have a jupyter notebook and you want to create a plot in one cell, and then write some markdown to explain it in the next, and then set the limits and talk again in the next. This is my code:

# %% %matplotlib inline import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2 * np.pi) y = np.sin(x ** 2) plt.plot(x, y); # %% Some markdown text to explain what going on before we zoom in on the interesting bit # %% plt.xlim(xmax=2); 

The beginning of each cell is marked with # %% above. The third cell shows an empty number.

I know plt.subplots(2) for building 2 graphs from one cell, but this does not allow me to have a markdown between graphs.

Thanks in advance for your help.

+5
source share
2 answers

This answer to a similar question says that you can reuse axes and figure from the previous cell. It looks like if you only have figure as the last element in the cell, it will display its graph again:

 # %% %matplotlib inline import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2 * np.pi) y = np.sin(x ** 2) fig, ax = plt.subplots() ax.plot(x, y); fig # This will show the plot in this cell, if you want. # %% Some markdown text to explain what going on before we zoom in on the interesting bit # %% ax.xlim(xmax=2); # By reusing `ax`, we keep editing the same plot. fig # This will show the now-zoomed-in figure in this cell. 
+4
source

The simplest thing I can think of is to extract the plot into a function that you can call twice. On the second call, you can also call plt.xlim to increase. So something like (using the %% notation for new cells):

 # %% %matplotlib inline import matplotlib.pyplot as plt import numpy as np # %% def make_plot(): x = np.linspace(0, 2 * np.pi) y = np.sin(x ** 2) plt.plot(x, y); make_plot() # %% Some markdown text to explain what going on before we zoom in on the interesting bit # %% make_plot() plt.xlim(xmax=2) 
+2
source

Source: https://habr.com/ru/post/1262499/


All Articles