python - 当 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.")
任何正确方向的观点都将不胜感激。谢谢!
解决方案
您需要扩展数据以使每个数据点具有 x 和 y。这是通过组合x
和y
形成一个与 具有相同形状的数组来完成的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)
推荐阅读
- javascript - 从此数组中获取过滤后的数组(具有相同首字母的值)
- oracle - 解密其中包含一些特殊字符的 Oracle CLOB 列
- arrays - 在数组中查找中间数;我了解如何做到这一点,但无法使其发挥作用。:/(珊瑚)
- linux - Dockerfile 通过获取脚本以动态方式设置运行时 ENV
- sql - SQL Server 每组添加行号
- bash - 如何在 bash 文件中使用 cat 和 EOF
- asp.net-mvc - 新网站的 msbuild 参数失败
- node.js - NodeJS getaddrinfo ENOTFOUND 未捕获
- tomcat - Tomcat 管理器 - 活动目录身份验证
- c# - Powershell not invoking method in a c# object