如果 fig = plt.figure() 在 Ipython Notebook 的另一个单元格中,add_subplot() 不工作

add_subplot() not working if fig = plt.figure() is in another cell in Ipython Notebook

我 运行 在 Ipython Notebook 中使用 matplotlib 遇到了一个奇怪的问题。这是代码:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(np.random.randn(10), 'k--')
ax2 = fig.add_subplot(212)
ax2.plot(np.random.randn(10), 'r--')

这很好用并生成了一个带有两个子图的内联图形。但是,如果我像这样将相同的代码放入两个单元格中:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(np.random.randn(10), 'k--')
ax2 = fig.add_subplot(212)
ax2.plot(np.random.randn(10), 'r--')

然后根本没有生成内联图像。

默认情况下,inline 后端会在单元格完全执行后关闭图形。

最好的方法是合并这些单元格。