Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent jupyter notebook from plotting figure returned by a function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading