'%matplotlib inline' causes error in following code

半城伤御伤魂 提交于 2019-12-20 07:29:24

问题


If I comment out '%matplotlib inline' the code runs fine But if I leave '%matplotlib inline' uncommented, 'fig, axes = plt.subplots(nrows=x_p, ncols=y_p)' starts to create blank plots, and following code triggers error as below. Any idea why?


回答1:


By default, figures are closed at the end of a cell. This means that pyplot (plt) has forgotten about the axes to work on in the next cell.

%config InlineBackend

tells us:

InlineBackend.close_figures= <Bool>
Current: False
Close all figures at the end of each cell.
When True, ensures that each cell starts with no active figures, but it also means that one must keep track of references in order to edit or redraw figures in subsequent cells. This mode is ideal for the notebook, where residual plots from other cells might be surprising.
When False, one must call figure() to create new figures. This means that gcf() and getfigs() can reference figures created in other cells, and the active figure can continue to be edited with pylab/pyplot methods that reference the current active figure.

The solution is thus to set .close_figures to False:

%config InlineBackend.close_figures=False

In order to prevent the automatic output of active figures at the end of a cell, you may then set plt.ioff().

import matplotlib.pyplot as plt

%matplotlib inline
%config InlineBackend.close_figures=False
plt.ioff()

fig, axes = plt.subplots(ncols=2)



来源:https://stackoverflow.com/questions/45341765/matplotlib-inline-causes-error-in-following-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!