0

Is there a way I can save a plot to a variable, and show it at multiple points in a notebook? Say I create a plot near the start of a notebook, then wayyyyy further down in the analysis it'd be relevant to look at that plot again.

Something like:

my_plot = plt.plot(plot_params)
plt.show()

Then later call:

plt.clf()
my_plot
plt.show()

This doesn't work, and I'm confused as to why, since the call to plt.plot(plot_params) should be stored in my_plot.

  • `my_plot` only holds a temporary reference to some lines in the subplot. You need to define a function. E.g. `def my_plot_func(): plt.plot(plot_params)` and then call that function twice. – JohanC Jan 13 '22 at 21:54
  • I think it’s possible display(fig) works? Where fig is a reference to the figure. – Jody Klymak Jan 14 '22 at 07:48

1 Answers1

0

plot returns a list of lines, not the plot itself. The plot itself is called a Figure in matplotlib. So you need to get this Figure and store it in a variable:

my_fig = my_plot[0].figure

To show it later in your Jupyter notebook, just type it as my_fig:

enter image description here

(or you keep your variable my_plot and get the figure later when you want to re-show it by my_plot[0].figure)

Stef
  • 28,728
  • 2
  • 24
  • 52