Concepts / Running Python Code in Jupyter Notebook

Running Python Code in Jupyter Notebook

Inside a Jupyter Notebook, that decision is controlled by a magic command, which is a special instruction recognized by the notebook environment that changes how figures are handled.

  • Programming

A Plot That Never Appears

A common first assumption is that any call to a plotting function will immediately put a picture on the screen. In many environments that assumption is false. Whether a figure appears depends on where the code runs and on how that environment has been configured. This article follows a single plot from the moment your code creates it to the moment it either appears or stays hidden, so you can predict the behavior in each situation.

What do you think happens?

You have a notebook cell containing only the plotting calls, and no display setting has been enabled. What do you expect to see in the output area of the notebook?

  • The plot appears automatically at the bottom of the cell

  • No figure appears, because nothing has told the notebook to show it

  • An error stops the cell before any plotting happens

Reveal answer
Answer:

No figure appears automatically, because nothing has told the notebook to show it.

The plotting calls build the figure, but building a figure and presenting it are separate jobs. Without a display instruction inside a Jupyter Notebook, the figure is not automatically placed on screen.

Building a Figure Versus Showing It

The wrong belief comes from confusing two separate jobs. One job is building the figure from data, which the plotting functions handle. The other job is presenting that figure to a viewer. Keeping these jobs apart is the key to understanding every behavior in this article.

matplotlib is the primary scientific plotting library in Python. It provides functions for making publication-quality visualizations such as line charts, histograms, and scatter plots. Visualizing data is a practical way to notice patterns and gain insight into an analysis, which is why a notebook-based workflow relies on it so heavily.

python

The two plotting calls above build a figure from the data. Nothing in those lines, by itself, says where the figure should be shown. Inside a Jupyter Notebook, that decision is controlled by a magic command, which is a special instruction recognized by the notebook environment that changes how figures are handled. Without that instruction, or outside a notebook altogether, the figure is not automatically placed on screen.

Plotting callplt.plot(...)Figure builtfrom the dataDisplay magicenabled?Sent to browsernotebook output areaFigure shownNot shownautomaticallyyesno
What happens between calling plt.plot and seeing an image in the notebook, and at which step can the figure fail to appear?

The figure can fail to appear at the decision point. Plotting succeeded and the figure exists, but the presentation step never ran. That is why the same plotting code can show a picture in one environment and show nothing in another.

Display Magics in the Notebook

Inside the Jupyter Notebook, you can show figures directly in the browser by using one of two commands: %matplotlib notebook or %matplotlib inline. Both are placed in a cell and run before the plotting code. The two commands are not interchangeable in behavior, so the choice matters.

Choosing Between the Two Display Commands

The practical difference is what the viewer can do with the figure. Compare the two commands side by side before choosing one for a task.

Feature%matplotlib notebook%matplotlib inline
Figure typeInteractive figureStatic plot
Viewer interaction inside the notebookResponds to the viewerFixed image
Source recommendationRecommended for interactionUsed for static output
Good fit whenYou want to explore or manipulate the plot in the notebookYou want a fixed image, such as material for a printed document

Choosing between the two display magics depends on whether the figure needs to respond to the viewer.

python

The magic line runs first, then the plotting code runs after it. Changing the first line to %matplotlib inline keeps the same plotting code but produces a static figure instead.

When plt.show Is Required

A display magic is not the only way to show a figure. The source notes that the setup it assumes runs in a Jupyter Notebook with a display magic enabled. If you are not using the notebook, or these magic commands, you have to call plt.show to display any of the figures. The same plotting code therefore needs different handling depending on the environment.

Plotting code runsJupyter Notebook withdisplay magic?Figure shown in celloutputCall plt.show()outside notebook or withoutmagicFigure displayedyesno
In which environments does a plot display automatically at the end of a cell, and in which does plt.show() have to be called explicitly?
python

Tracing One Cell Step by Step

Worked example

Following a Plot Through Two Environments

The same plotting code is run in two places: once in a Jupyter Notebook cell with %matplotlib inline enabled, and once in a plain Python script run outside a notebook with no display magic. Determine whether the figure is displayed in each case.

  1. 1
    Identify the build step

    In both places, plt.plot builds the figure from the data. The build step is the same, so the difference must come from the display step.

  2. 2
    Check the notebook case

    The notebook cell has a display magic enabled, so the notebook sends the figure to the browser and it appears in the output area.

  3. 3
    Check the script case

    The script is outside a notebook and has no display magic, so the figure is not displayed automatically. A call to plt.show() is needed.

  4. 4
    Compare the outcome

    The plotting code is identical. Only the environment and the presence of a display instruction changed the result.

Result

In the notebook with a display magic, the figure appears automatically. In the plain script, the figure appears only if plt.show() is called.

Python 2 and Python 3 Mismatch

The second misconception concerns the language version rather than the notebook. There are two major versions of Python in wide use: Python 2, more precisely 2.7, and Python 3. Python 2 is no longer actively developed. Because Python 3 contains major changes, Python 2 code usually does not run on Python 3. The belief to avoid is that code written for one version will simply run on the other.

python

The first line is a Python 2 style print statement. Running it under Python 3 raises a syntax error, because print is a function in Python 3 and needs parentheses. This is one example of the kind of change that stops older code from running. For new projects, the source recommends using the latest Python 3.

Mistakes Beginners Make with Display

  • Common mistake

    Assuming a plotting call always puts a picture on screen

    What it looks like

    A cell contains only plt.plot(...) with no display setting, and the learner expects a figure to appear.

    Why it fails

    Building a figure and displaying it are separate jobs. The display step depends on the environment.

    Do this instead

    Enable a display magic inside a notebook, or call plt.show() outside one.

  • Common mistake

    Treating %matplotlib notebook and %matplotlib inline as identical

    What it looks like

    Using inline when the figure needs to be explored interactively, or using notebook when a fixed image is wanted.

    Why it fails

    The two commands differ in whether the figure is interactive or static.

    Do this instead

    Choose notebook for interaction and inline for a static plot.

  • Common mistake

    Calling plt.show() in a notebook without understanding its role

    Why it fails

    The notebook display is controlled by the display magic, so the need for an explicit call depends on the environment.

    Do this instead

    Learn which environments need plt.show() and which rely on the display magic.

  • Common mistake

    Running Python 2 code in a Python 3 environment and expecting it to work

Practice Predicting Display Behavior

EASY

A colleague runs a plotting script from a terminal, with no notebook and no display magic, and sees nothing appear. Explain what is missing and what single call would make the figure display.

Hints
  • Think about which job is missing: building the figure or presenting it.
  • The environment here is outside a notebook, so consider what the source says is required.
MEDIUM

You want an interactive plot you can zoom and explore inside a Jupyter Notebook. Which display magic do you place before your plotting code, and why does the other option fall short?

Hints
  • Compare what each magic produces: interactive versus static.
  • The source recommends the option that provides an interactive environment.

Key Takeaways

  • A plotting call builds a figure from data, but presenting that figure is a separate step that depends on the environment.
  • Inside a Jupyter Notebook, %matplotlib notebook gives an interactive figure and is recommended for interaction, while %matplotlib inline gives a static plot.
  • Outside a notebook, or without a display magic, you must call plt.show() to display figures.
  • Python 2 code usually does not run on Python 3 because Python 3 contains major changes, so new projects should use the latest Python 3.

More concepts starting with R