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?
To draw multiple plots in the R Language, we draw a basic plot and add an overlay line plot or scatter plot by using the lines() and the points() function. This line and scatter plot overlay can be drawn on top of any layer in the R Language.
Combine Plots in Same Axes By default, new plots clear existing plots and reset axes properties, such as the title. However, you can use the hold on command to combine multiple plots in the same axes. For example, plot two lines and a scatter plot. Then reset the hold state to off.
Overlay plots are different plots (like vectors and contours) that are drawn on top of each other, and possibly on top of a map. There are many different ways that one can create overlay plots: Use the overlay procedure (this is the best method)
There are essentially two ways to tackle this.
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?
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:
'%matplotlib inline' causes error in following code
Manipulate inline figure in IPython notebook
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With