首页 > 解决方案 > 当 x 和 y 表示为 1d 数组时,如何使用 matplotlib 创建 3d 曲面图?

问题描述

我想从数组 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)

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

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

标签: pythonnumpymatplotlibsurface

解决方案


您需要扩展数据以使每个数据点具有 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)

推荐阅读