使用 Python 在三维 space 中绘制条件函数

Plotting a condition function in three dimensional space with Python

问题:我想在三维 space 上绘制一个双变量条件函数 f(x,y),这是我的代码

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)

我在 Google Colab 上键入此代码,它在第 3 行向我发送了如下错误

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

0 < y**2 的结果是一个布尔数组,您将其与单个值 (True) 进行比较;这就是错误的来源。

当处理这样的条件值时,最好将 boolean array indexing 与 NumPy 结合使用:

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

顺便说一下,为了使用 3D 图,您应该看看 mplot3d Toolkit:

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