0

I have a simple function:

def return_fig():
    fig = plt.figure()
    plt.plot([1,2,3,4,5],[1,2,3,4,5])
    return fig

In a jupyter notebook, I define this function and

import matplotlib.pyplot as plt

In a new cell, I have

figure = return_fig()

When I execute the cell, the figure gets shown immediately. However, I just want the figure object to exist, and to be able to show it with plt.show() later on. This is what happens within a regular python script, but not within a jupyter notebook. What am I missing?

sodiumnitrate
  • 2,899
  • 6
  • 30
  • 49
  • 1
    To add some more context to your 'what is missing' question, recently Jupyter tries to detect a plot object being made in a cell and then by default tries to display it. You'll see a lot of code in old answers & resources invoking the plot object or showing it in the last line of a cell; however, that is no longer the default behavior. l'mhadi's answer helps you see how to opt in to selectively that not being the case by telling Jupyter there is no active plot object. – Wayne Feb 18 '23 at 17:19

1 Answers1

1

Maybe plt.close() helps.

def return_fig():
    fig = plt.figure()
    plt.plot([1,2,3,4,5],[1,2,3,4,5])
    plt.close(fig)
    return fig

Run:

>>> figure = return_fig()
>>> figure

Output:

enter image description here

I'mahdi
  • 23,382
  • 5
  • 22
  • 30