0

I like to only show a matplotlib figure with an explicit show(fig). But Jupyter automatically shows all created figures.

This link has a workaround, but it is essentially just capturing all the output of a cell. I don't want to do that.

Related:

PS: I am actually using seaborn, not matplotlib directly.

HappyFace
  • 3,439
  • 2
  • 24
  • 43
  • Have you tried `plt.ioff()` before defining any figure object? This might help: https://stackoverflow.com/a/35949684/7789963 – medium-dimensional Jun 07 '22 at 13:56
  • 1
    You can also specify the magic command ```%%capture``` at the beginning of the Jupyter cell. This will prevent all output from that cell – Robert Jun 07 '22 at 14:01

1 Answers1

0

Using plt.ioff disables interactive mode and storing figure in a variable won't display any output:

import matplotlib.pyplot as plt 
import numpy as np
import seaborn as sns 

plt.ioff()
sns.set_theme(style="darkgrid")

# Load an example dataset with long-form data
fmri = sns.load_dataset("fmri")

# Plot the responses for different events and regions
fig = sns.lineplot(x="timepoint", y="signal",
             hue="region", style="event",
             data=fmri)

But using plt.show() reverses the effect and show the output figure:

# Import modules here
plt.ioff()

# Set theme and load data here
fig = sns.lineplot(x="timepoint", y="signal",
             hue="region", style="event",
             data=fmri)

plt.show()

How the Jupyter Notebook output looks like when the above code is used:

enter image description here


The code for plotting the Timeseries plot comes from here.

medium-dimensional
  • 1,974
  • 10
  • 19