I want to build a plot with multiple lines, one cell at a time, and show the intermediate results. However, the plot is only displayed in the first cell.
Here is an example (if there is a preferred way to share a notebook, please let me know, this is my first time here):
Cell 1:
import matplotlib.pyplot as plt
from numpy import linspace, sin, cos
t = linspace(0, 6.28, 100)
fig, ax = plt.subplots()
ax.plot(t, sin(t))
This shows a sine plot.
Cell 2:
ax.plot(t, cos(t))
I expected the output to be a plot showing both a sine and a cosine wave. However, no plot is shown, and the only output is (as expected) [<matplotlib.lines.Line2D at 0x7faf21806350>].
There isn’t an open matplotlib figure object in the second cell, and so Jupyter is just displaying the result of the expression on the last line.
Your second cell can also be:
ax.plot(t, cos(t))
ax.figure
The variable you assigned it to is probably easier & clearer though, and I really only mention that attribute option because might come across a different Matplotlib case where you didn’t previously assign a variable and need the associated figure object.
Your first cell would be cleaner as:
import matplotlib.pyplot as plt
from numpy import linspace, sin, cos
t = linspace(0, 6.28, 100)
fig, ax = plt.subplots()
ax.plot(t, sin(t));
So that it is only displaying the plot and not also the result of the expression ax.plot(t, sin(t).
The ; becomes the last expression there and since it returns nothing, nothing additional is displayed.
You created a Matplotlib plot object and so it will get displayed. It is a newer feature. You’ll see a lot of old code with plt.show() as the last line. Jupyter determining now there is an active figure makes it easier.
In general, the expression of the last line of a cell will get shown as this is the default. Plus anything you sent to active output along the way in that cell, and any plot.
By the way, I specified ‘default’ because you can change it during notebook’s run, see here & the comments on that answer and on the original question.