Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the current figure when using ipython notebook with %matplotlib inline?

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?

like image 540
user26767 Avatar asked Jul 15 '15 21:07

user26767


People also ask

What happens if I dont use %Matplotlib inline?

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.

How do you dynamically update a plot in a loop in IPython notebook?

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).

Do We Still Need %Matplotlib inline?

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.


1 Answers

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

like image 84
unutbu Avatar answered Sep 21 '22 19:09

unutbu