2017-12-26 10 views
0

は、私は次のコードを持っている:matplotlibに複数の関数をプロットするにはどうすればよいですか?

def f(x): 
    return x 

def g(x): 
    return x*x 

from math import sqrt 
def h(x): 
    return sqrt(x) 

def i(x): 
    return -x 

def j(x): 
    return -x*x 

def k(x): 
    return -sqrt(x) 

functions = [f, g, h, i, j, k] 

をそして今、私は、これらの機能をプロットしようとしています。

私は

plt.plot(f(x), g(x), h(x))

を試してみましたが、私は次のエラーを取得する:

TypeError: only length-1 arrays can be converted to Python scalars

私は私は2つのソリューションを持っている平方根を使用していますので、これは理解。

plt.plot(*functions)

何かアドバイス:しかし、本当に、私のような何かをしようとしていますか?

+0

をしてください、検証可能な例を提供しても、それが盗聴だ:それはあなたがしようとしたかを示してこれまでのところ。 – IMCoins

答えて

3

math.sqrtは、スカラー値のみを受け入れます。 使用numpy.sqrtがリストまたはnumpyの配列内の各値の平方根を計算する:

In [5]: math.sqrt(np.array([0,1])) 
TypeError: only length-1 arrays can be converted to Python scalars 

In [6]: np.sqrt(np.array([0,1])) 
Out[6]: array([ 0., 1.]) 

import numpy as np 
import matplotlib.pyplot as plt 

def f(x): 
    return x 

def g(x): 
    return x*x 

def h(x): 
    return np.sqrt(x) 

def i(x): 
    return -x 

def j(x): 
    return -x*x 

def k(x): 
    return -np.sqrt(x) 

x = np.linspace(0, 1, 100) 
functions = [f, g, h, i, j, k] 
for func in functions: 
    plt.plot(func(x), label=func.__name__) 
plt.legend(loc='best') 
plt.show() 

enter image description here

関連する問題