I could not find answer for this, so please let me ask here.
I would like to keep the current figure in ipython notebook when using %matplotlib inline
. Is that possible?
For example, I want to plot 2 lines in a graph
plt.plot([1,2,3,6],[4,2,3,4])
plt.plot([3.3, 4.4, 4.5, 6.5], [3., 5., 6., 7.])
If I put those two command lines in a cell it is ok. The graph shows two lines. However, if I put them separately into two cells, when the second cell (plt.plot([3.3, 4.4, 4.5, 6.5], [3., 5., 6., 7.])) is executed, the previous plot(plt.plot([1,2,3,6],[4,2,3,4])) is cleared. I want to plot a graph with the line for the first cell and a graph with the two lines for the second cell.
I looked up the website It explicitly clears the plot by
plt.cla() # clear existing plot
but it is bit confusing, since it automatically clears anyway.
Is there any command to not clear (or keep) the previous plot like "hold on" in Matlab?
In the current versions of the IPython notebook and jupyter notebook, it is not necessary to use the %matplotlib inline function. As, whether you call matplotlib. pyplot. show() function or not, the graph output will be displayed in any case.
Try to add show() or gcf(). show() after the plot() function. These will force the current figure to update (gcf() returns a reference for the current figure).
So %matplotlib inline is only necessary to register this function so that it displays in the output. Running import matplotlib. pyplot as plt also registers this same function, so as of now it's not necessary to even use %matplotlib inline if you use pyplot or a library that imports pyplot like pandas or seaborn.
Use ax.plot
instead of plt.plot
to make sure you are plotting to the same axes both times. Use fig
(in the second cell) to display the plot.
In cell 1:
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3,6],[4,2,3,4])
In cell 2:
ax.plot([3.3, 4.4, 4.5, 6.5], [3., 5., 6., 7.])
fig
yields
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