2017-12-26 3 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

나는 두 가지 솔루션을 가지고 제곱근을 사용하고 있기 때문입니다 그림.

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

관련 문제