Medulla Oblongata
Medulla Oblongata

Reputation: 3961

Python controlling figure outputs from functions

If I generate a figure from within a function, is there a simple way to not show the figure output? My following function always outputs a figure even when I have a _ when calling the function.

import numpy as np
import matplotlib.pyplot as plt

def myfun(a,b):
    x = np.linspace(1,10,100)
    y = np.linspace(2,20,100)
    z = a*x - b*y

    plt.figure()
    plt.plot(x,z)

    myfig = plt.show()

    return z, myfig

z, _ = myfun(2,3)

It would be ideal to not introduce any more input parameters in myfun.

Upvotes: 2

Views: 64

Answers (2)

Medulla Oblongata
Medulla Oblongata

Reputation: 3961

It's not an elegant way of doing it, but including a showfig input option seems to work. Let showfig=1 to display the figure, and showfig=0 to not show a figure and instead let myfig = a string.

import numpy as np
import matplotlib.pyplot as plt

def myfun(a,b,showfig):
    x = np.linspace(1,10,100)
    y = np.linspace(2,20,100)
    z = a*x - b*y

    if showfig == 1:
        plt.figure()
        plt.plot(x,z)
        myfig = plt.show()
        return z, myfig
    else:
        myfig = 'figure not shown'        
        return z, myfig

z, myfig = myfun(2,3,0)

Upvotes: 0

elyase
elyase

Reputation: 40973

You can do it like this:

def myfun(a,b):
    x = np.linspace(1,10,100)
    y = np.linspace(2,20,100)
    z = a*x - b*y

    fig, ax = plt.subplots()
    ax.plot(x,z)
    return z, fig

Afterwards you can do:

z, fig = myfun(2,3)  #  nothing is shown
plt.show(fig)        #  now show the figure

Upvotes: 2

Related Questions