7

I am curious to understand the below explained behavior of inline matplotlib plots in the Jupyter notebook. I will show three cases:

Case 1: Importing and plotting in separate cells. In this case, the plot appears after executing both the cells once consecutively.

enter image description here


Case 2: Importing and plotting in the same cell. In this case, the plot doesn't appear when the cell [1] is executed once (no figure in the image below). The plot however appears when the same cell [1] is executed again. This is the issue asked as the question below.

enter image description here


Case 3: Adding %matplotlib inline to Case 2, all in one cell. In this case, as expected, the plot appears after executing the cell once. So no issues here at all.

enter image description here


Question

Similar post has been asked here before which only mentioned Cases 2 and 3. The comment by ImportanceOfBeingErnest on the linked post clarified that the Jupyter might be configured in a way to use %matplotlib inline by default.

So my question is not why Cases 1 and 2 work without %matplotlib inline, rather I would like to understand

  • Why the cell [1] in Case 2 needs to be executed twice to show the plot while the cells [1] and [2] in Case 1 works when executed only once? Is import matplotlib.pyplot as plt invoking/activating the backend differently under the hood when called in different cells?

System specs

import sys
print (sys.version)
# 3.6.5 |Anaconda, Inc.

import matplotlib
print (matplotlib.__version__)
# 2.2.2

! jupyter notebook --version
# 5.5.0
Sheldore
  • 35,129
  • 6
  • 43
  • 58
  • I don't know the answer, but there are other cases where [issuing a command twice](https://stackoverflow.com/a/41251483/4124317) helps, as well as [the first cell behaving diffently](https://github.com/jupyter/notebook/issues/3385). – ImportanceOfBeingErnest Jan 23 '19 at 16:09
  • @ImportanceOfBeingErnest: Thanks for the response and the links. I am glad that this wasn't a trivial issue. It doesn't hinder any work but I noticed this today and was curious to know what's up. – Sheldore Jan 23 '19 at 16:20
  • All cases plot the figure when executing the cell. Tested with `notebook 6.4.3`, `jupyter 1.0.0`, and `jupyterlab 3.1.7`. I'm voting to close this as not reproducible. – Trenton McKinney Sep 28 '21 at 20:58

0 Answers0