0

Problem: I want to plot a two varibles condition function f(x,y) on three dimesional space and here is my code

from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0, 10, 200)
y = np.linspace(0, 10, 200)
if (0<y**2) == True and (y**2<x) == True: 
 z = 3/4
elif (y == 0) == True or (0<=x<=y**2) == True: 
 z = 0
plt.plot(x,y,z)

I type this code on Google Colab and it send me an error at line 3 as following

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

0

1 Answer 1

1

The result of 0 < y**2 is a boolean array and you're comparing it to a single value (True); that's where that error comes from.

When dealing with conditional values like this, its best to use boolean array indexing with NumPy:

z = np.zeros(200)
z[(0 < y ** 2) & (y ** 2 < x)] = 3 / 4

By the way, in order to use 3D plots you should take a look at the mplot3d Toolkit:

enter image description here

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 10, 200)
y = np.linspace(0, 10, 200)
z = np.zeros(200)

z[(0 < y ** 2) & (y ** 2 < x)] = 3 / 4

fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.plot(x, y, z)

plt.show()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.