Enable plotting in same notebook cell which imports matplotlib.pyplot by benjimin · Pull Request #11916 · ipython/ipython (original) (raw)
This fixes a bug for Jupyter notebooks, that plot commands often do not display until the second time their cell is executed. jupyter/notebook#3691
Specifically, inline display of plots was broken for the first cell which imports matplotlib.pyplot
, but does works in subsequent cells (or even if the same cell is evaluated a second time). This particularly affected libraries that lazily import matplotlib, such as xarray:
In [1]: import xarray, numpy as np In [2]: x = xarray.DataArray(np.random.random((5,5))) In [3]: x.plot() # did not work In [4]: x.plot() # did work
The problem related to circular imports between matplotlib and ipython. The import of the matplotlib.pyplot
module executes a call to IPython.core.pylabtools:activate_matplotlib
which in turn imports matplotlib.pyplot
(while it is still only partially initialised e.g. the matplotlib
module may not yet have a pyplot
attribute). By using a slightly different import syntax it is possible to avoid causing an exception here.
Note, there is also a partial work-around in ipykernel.pylab.backend_inline:_enable_matplotlib_integration
which catches the import/attribute error and in that case reschedules activate_matplotlib
until after the cell finishes executing (i.e. after import completes). The problem was that it was late to schedule flush_figures
(as the event is already triggering before the callback gets registered), which is why plotting only worked in subsequent cell evaluations.
Tested on python 3.6.7.