Auto-show in Jupyter notebook

The doc for pyplot.show() says: “The jupyter backends (activated via %matplotlib inline, %matplotlib notebook, or %matplotlib widget), call show() at the end of every cell by default. Thus, you usually don’t have to call it explicitly there.”

In a Jupyter notebook (Pyodide 0.24.1 kernel and matplotlib 3.5.2), my cells run the cells below.

import matplotlib.pyplot as plt

%matplotlib inline

fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')

Before auto-showing the figure, the cell outputs: <matplotlib.legend.Legend at 0x440c740>. If the cell automatically calls show(), why doesn’t it hide this children? Thanks.

1 Like

Jupyter outputs the result of the last line in your cell, if not None. In this case, it’s outputting the return value of the legend() call.

You can suppress this with a semicolon, like:

ax.legend(title='Fruit color');

Or capture the return value like this:

legend = ax.legend(title='Fruit color')

It’s not actually related to Matplotlib.

1 Like