Skip to main content
 首页 » 编程设计

Python 控制函数的图形输出

2024年10月25日11lvdongjie

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

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中引入更多的输入参数。

请您参考如下方法:

你可以这样做:

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