Enable plotting in same notebook cell which imports matplotlib.pyplot #11916
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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:The problem related to circular imports between matplotlib and ipython. The import of the
matplotlib.pyplot
module executes a call toIPython.core.pylabtools:activate_matplotlib
which in turn importsmatplotlib.pyplot
(while it is still only partially initialised e.g. thematplotlib
module may not yet have apyplot
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 reschedulesactivate_matplotlib
until after the cell finishes executing (i.e. after import completes). The problem was that it was late to scheduleflush_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.