首页 > 解决方案 > 通过定义函数构建 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

标签: pythonnumpy3d

解决方案


你的错误很少。

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

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

  3. 在第一个版本中,您使用两个列表z = []zz = []然后追加- 但zzz函数中,您只使用一个列表 - 这可能是0D, 2D,的最大问题3D

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

顺便提一句:

您还可以放置一些空格以使代码更具可读性 - 即。之后,的空间,周围的空间=等。

更多:PEP 8——Python 代码风格指南


推荐阅读