knowledge_seeker
knowledge_seeker

Reputation: 937

How to plot a function in matplotlib when getting the following error:ValueError: The truth value of an array with more than one element is ambiguous

Here is the function I am trying to plot

def f(x):
    return 50 * (1 / (1 + ((50/5)-1) * e ** -max(0, 0.1 * x)))

I am getting the following error when trying to plot it using matplotlib: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I believe it is because of the -max(0, 0.1 * x) part of my function.

Here is the full version of my matplotlib code:

import matplotlib.pyplot as plt
import numpy as np
from math import e

# 100 linearly spaced numbers between -10 and 100
x = np.linspace(-10,100,200)

def f(x):
    return 50 * (1 / (1 + ((50/5)-1) * e ** -max(0, 0.1 * x)))

# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# plot the function
plt.plot(x,f(x), 'r')

# show the plot
plt.show()

Researching this error leads me to find out that while the max() function normally evaluates numbers, due to it being passed x which is a np.linspace() and not a number then it is unable to evaluate it.

How can I plot the f(x) function without changing it internally (as this would ruin some unit tests that I have)

Upvotes: 0

Views: 148

Answers (1)

t.o.
t.o.

Reputation: 879

I reread your question, and you want to know if the function can be run as-is without modification, and the answer is yes. You need to evaluate it point-by-point with the current design.

I do this by creating a zeros array of the length of numbers that you want to evaluate, and insert the function values into each index. The result is similar to the previous answer.

import matplotlib.pyplot as plt
import numpy as np
from math import e

# 100 linearly spaced numbers between -10 and 100
N=200
x = np.linspace(-10,100,N)

def f(x):
    return 50 * (1 / (1 + ((50/5)-1) * e ** -max(0, 0.1 * x)))

f_eval = np.zeros(N)
for idx, i in enumerate(x):
    f_eval[idx] = f(i)


# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# plot the function
plt.plot(x,f_eval, 'r')

# show the plot
plt.show()

result

Upvotes: 2

Related Questions