当 x 和 y 表示为一维数组时,如何使用 matplotlib 创建 3d 曲面图?

How to create a 3d surface plot with matplotlib when x and y are stated as 1d arrays?

我想从数组 x、y、z 创建一个 3d 曲面图,其中 len(x) 和 len(z) = 250 并且 len(y)= 7

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
import numpy as np


fig = plt.figure()
ax = fig.gca(projection='3d')

surf = ax.plot_surface(X,Y,Z, cmap=cm.coolwarm,
                   linewidth=0, antialiased=False)

给我这个错误:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

我试过网状网格:

T,U=np.meshgrid(x,b)
surf = ax.plot_surface(T,U,y, cmap=cm.coolwarm,
                   linewidth=0, antialiased=False)

但这产生了: 值错误("Argument Z must be 2-dimensional.")

任何方向正确的观点都将不胜感激。谢谢!

您需要扩展数据,使每个数据点都有 x 和 y。 这是通过组合 xy 形成一个与 z.

形状相同的数组来完成的

您可以使用 np.meshgrid:

import numpy as np

x = np.array([1, 2, 3])
y = np.array([5, 6, 7, 8])
z = np.random.rand(4, 3) 

# make sure to take a look hat the keyword 
# indexing : {‘xy’, ‘ij’} and check some (x,y,z) pairs
# to make sure that the values are correct 

xv, yv = np.meshgrid(x, y)
print(xv)
print(yv)
print(xv.shape)
print(yv.shape)
print(z.shape)