Joshua M. Moore
Joshua M. Moore

Reputation: 399

How do I plot multiple functions in matplotlib?

I have the following code:

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]

And now I'm trying to plot these functions.

I tried

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

but I get the following error:

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

I figure this is because I'm using the square root which has two solutions. But really, I'm trying to do something like:

plt.plot(*functions)

Any advice?

Upvotes: 0

Views: 1675

Answers (1)

unutbu
unutbu

Reputation: 880797

math.sqrt accepts only scalar values. Use numpy.sqrt to compute the square root of each value in a list or NumPy array:

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

Upvotes: 3

Related Questions