Python控制函数的图形输出

时间:2015-01-14 21:33:32

标签: python function matplotlib

如果我从函数中生成一个数字,有没有一种简单的方法可以不显示数字输出?即使我在调用函数时有_,我的以下函数也会输出一个数字。

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)

myfun中不再引入任何输入参数是理想的。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

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

之后你可以这样做:

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

答案 1 :(得分:0)

这不是一种优雅的方式,但包含showfig输入选项似乎有效。让showfig=1显示图形,showfig=0显示图形,而不是让myfig =字符串。

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)