Moritz
Moritz

Reputation: 5408

jupyter notebook prevent plot from showing up on class initialization

If I write following class:

from matplotlib import pyplot as plt
import numpy as np

class FigureShowingUp:

    def __init__(self):
        self.fig, self.ax = plt.subplots(ncols=1, figsize=(8,6))

    def make_plot(self):
        x = np.linspace(0, 1)
        y = np.random.normal(loc=0, scale=1, size=len(x))
        self.ax.scatter(x,y)

And import it in a notebook like:

from test_fig_class import FigureShowingUp
test = FigureShowingUp()

The plot always shows up upon initialization. How do I prevent that ?

Upvotes: 0

Views: 307

Answers (1)

Paul Brodersen
Paul Brodersen

Reputation: 13031

I don't use notebooks very much, but presumably you have to turn off interactive plotting:

from matplotlib import pyplot as plt; plt.ioff()

Then show the figure after making the plot:

def make_plot(self):
    x = np.linspace(0, 1)
    y = np.random.normal(loc=0, scale=1, size=len(x))
    self.ax.scatter(x,y)
    plt.show()

Upvotes: 2

Related Questions