6
votes

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?

1

1 Answers

9
votes

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: