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.
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.
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.
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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…