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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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:
- How to keep the current figure when using ipython notebook with %matplotlib inline?
- How to add plot commands to a figure in more than one cell, but display it only in the end?
- How do I show the same matplotlib figure several times in a single IPython notebook?
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:
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0