python - 通过定义函数构建 3D 对象
问题描述
我有函数 z[i][j]=func(x[i],y[j]),其中 x 和 y 从 -1 变为 1,步长为 0.1。
当 x<0 和 z=cos(x+y) 当 x>0 时,需要构建 z=sin(x+y) 的 3D 对象
我做了一些变化(1 工作正常(我猜)),但需要定义一个函数
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x=np.linspace(-1,1,21)
y=np.linspace(-1,1,21)
x1,y1= np.meshgrid(x,y)
z = []
for i in x:
zz = []
for j in y:
if i<0:
zz.append(np.sin(i+j))
else:
zz.append(np.cos(i+j))
z.append(zz)
fig=plt.figure(figsize=(5,6))
ax=fig.add_subplot(1,1,1,projection='3d')
ax.contour3D(x,y,z,10,cmap='inferno')
plt.show
UPD:我必须在我的工作代码中导入代码(函数),但不知道如何使它与 3D 绘图一起使用)
import numpy as np
def func(x,y):
if (x<0):
return [np.sin(x+y)]
elif (x>0):
return [np.cos(x+y)]
else:
return [0]
print(func(1,4))
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-1,1,21)
y=np.linspace(-1,1,21)
def fun(i,j):
for i in x:
fun = []
for j in y:
if i<0:
fun.append(np.sin(i+j))
else:
fun.append(np.cos(i+j))
fig=plt.figure(figsize=(5,6))
ax=fig.add_subplot(1,1,1,projection='3d')
ax.contour3D(x,y,fun(x,y),10,cmap='inferno')
plt.show
和错误消息:
/usr/local/lib/python3.7/dist-packages/matplotlib/contour.py in _check_xyz(self, args, kwargs)
1506
1507 if z.ndim != 2:
-> 1508 raise TypeError(f"Input z must be 2D, not {z.ndim}D")
1509 if z.shape[0] < 2 or z.shape[1] < 2:
1510 raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
我真的很感谢所有的帮助:3
解决方案
你的错误很少。
您使用相同的名称
def fun()
,fun = []
有时会造成大问题你为参数使用了错误的名字——你有
fun(i, j)
但后来你使用了for ... in x:
,for ... in y:
所以你需要fun(x, y)
在第一个版本中,您使用两个列表
z = []
,zz = []
然后追加- 但zz
在z
函数中,您只使用一个列表 - 这可能是0D
,2D
,的最大问题3D
您必须使用
return ...
将值从函数发送到主代码。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# --- functions ---
def fun(x, y):
results = [] # z = []
for i in x:
row = [] # zz = []
for j in y:
if i < 0:
row.append(np.sin(i+j))
else:
row.append(np.cos(i+j))
results.append(row)
return results
# --- main ---
x = np.linspace(-1, 1, 21)
y = np.linspace(-1, 1, 21)
fig = plt.figure(figsize=(5, 6))
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.contour3D(x, y, fun(x, y), 10, cmap='inferno')
plt.show()
顺便提一句:
您还可以放置一些空格以使代码更具可读性 - 即。之后,
的空间,周围的空间=
等。
推荐阅读
- javascript - 如何停止对“dragover”事件的口吃
- algorithm - 在合并排序中的上一次递归期间,有什么方法可以将返回值用作同一函数的参数
- javascript - 用 js 附加回显元素
- java - 我的 JavaFX 项目在 EventHandler 处停止运行代码
- python - 在 numpy 中保持维度的数组的索引列表
- linux - 如何将 find 的所有 BASH 结果输出到单个变量?更多细节在帖子中
- r - 列表到数据框指定列名
- ruby - 强制macos系统降级ruby系统
- r - 如何调整 plotly hovermode 'x' 选项以在没有额外美学和重叠坐标的情况下工作?
- swift - Swift:工具栏项目出现在随机位置