通过定义函数构建 3D 对象

Build 3D Object by define a function

我有函数 z[i][j]=func(x[i],y[j]),其中 x 和 y 以步长 0.1 从 -1 变为 1。

需要构建 3D 对象,当 x<0 时,z=sin(x+y),当 x>0 时,z=cos(x+y)

我做了一些改动(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

更新:我必须在我的工作代码中导入下面的代码(函数),但不知道如何让它与 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

你的错误很少。

  1. 你对 def fun()fun = [] 使用相同的名称,有时这会造成大问题

  2. 你使用了错误的参数名称 - 你有 fun(i, j) 但后来你使用 for ... in x:, for ... in y: 所以你需要 fun(x, y)

  3. 在第一个版本中,您使用两个列表 z = []zz = [] 并在 z 中附加 zz - 但在功能中您只使用一个列表 - 这可能是 0D2D3D

    的最大问题
  4. 您必须使用 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()

顺便说一句:

您还可以放置一些 space 以使代码更具可读性 - 即。 space 在 , 之后,space 大约 =,等等

更多:PEP 8 -- Style Guide for Python Code