How to keep the current figure when using ipython

2020-07-20 04:49发布

问题:

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?

回答1:

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