Home > database >  Plotting a condition function in three dimensional space with Python
Plotting a condition function in three dimensional space with Python

Time:01-26

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()

CodePudding user response:

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 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()
  •  Tags:  
  • Related