首页 > 解决方案 > 绘制 3D 图形的列表操作(ndim - 错误)

问题描述

(这不是我的实际问题,但我正在对其进行建模以简化问题)

我有两个大小不相等的数据集。

x_values = [1,2,3]
y_values = [4,5]

让我们假设我有一个函数 f,这样

def f(x,y):
    return x + y

我想要的是某种代码,例如从每个数组中获取每个值并创建 (x,y) 对

(1,4) , (1,5), (2,4), (2,5) , (3,4) ,(3,5)

然后将它们放入我们获得 z_values 的 f 中。

5, 6, 6, 7, 7, 8

现在我想根据所有 (x,y,z) 坐标绘制一个 3D 图,这样

(1,4,5) , (1,5,6), (2,4,6), (2,5,7) , (3,4,7) ,(3,5,8)

所以我必须在 3D 绘图上绘制这些点。

编辑:我解决了这个问题,但是当我尝试绘制 3D 图形时出现错误

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

xs = [1,2,3]
ys = [4,5]

def f(x,y):
    return x+y

A = list((x,y) for x in xs for y in ys)

New_points = []
for (x,y) in A:
    z = f(x,y)
    New_points.append((x,y,z))

    
X= list(New_points[i][0] for i in range(len(New_points)))
Y = list(New_points[i][1] for i in range(len(New_points)))
Z= list(New_points[i][2] for i in range(len(New_points)))


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, color='b')
plt.show()

错误是:

line 1613, in plot_surface
if Z.ndim != 2:
AttributeError: 'list' object has no attribute 'ndim'

请帮忙!!

标签: pythonarrayslistmatplotlibmatrix

解决方案


你快到了,你只需要plot_surface

Z = f(X,Y)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X,Y,Z)

更新:对于通用功能:

xs = [1,2,3]
ys = [4,5]

X,Y = np.meshgrid(xs, ys)

Z = np.array([[f(x,y) for y in ys] for x in xs])

ax.plot_surface(X,Y,Z)

输出:

在此处输入图像描述


推荐阅读