7

In one of the cells in my notebook, I already plotted something with

myplot = plt.figure() plt.plot(x,y)

Now, in a different cell, I'd like to plot the exact same figure again, but add new plots on top of it (similar to what happens with two consecutive calls to plt.plot()). What I tried was adding the following in the new cell:

myplot plt.plot(xnew,ynew)

However, the only thing I get in the new cell is the new plot, without the former one.

How can one achieve this?

JLagana
  • 1,224
  • 4
  • 14
  • 33

1 Answers1

9

There are essentially two ways to tackle this.

A. Object-oriented approach

Use the object-oriented approach, i.e. keep handles to the figure and/or axes and reuse them in later cells.

import matplotlib.pyplot as plt
%matplotlib inline

fig, ax=plt.subplots()
ax.plot([1,2,3])

Then in a later cell,

ax.plot([4,5,6])

Suggested reading:

B. Keep figure in pyplot

The other option is to tell the matplotlib inline backend to keep the figures open at the end of a cell.

import matplotlib.pyplot as plt
%matplotlib inline

%config InlineBackend.close_figures=False # keep figures open in pyplot

plt.plot([1,2,3])

Then in a later cell

plt.plot([4,5,6])

Suggested reading:

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Neither A nor B work for me, running the latest VS Code on Windows or on Linux. In the second cell, I just get one line of text output (no figure): [] – Mark Ebden Apr 25 '22 at 14:08