Matplotlib Jupyter – Fixing ‘%matplotlib inline’ Error

jupyter-notebookmatplotlib

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?

enter image description here

enter image description here

enter image description here

Best Answer

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)

enter image description here

Related Question