我想用 matplotlib 绘制 3d 图。
数据如下:我有一个矩阵,每行包含 3d 图的 Y 坐标。每行第一个元素是 3d 图的 X 坐标。最后,第二个矩阵在 X、Y 位置包含每个点的高值。因此,第二个矩阵包含我的 Z 坐标。这两个矩阵都是 Python 的数组数组。我想知道如何转换数据以获得:
- 每个 1d 信号对应于一个 X 的图,像这样(在线提供照片)
- 相同数据的线框图,像这样
我已经为线框作品编写了一个辅助函数,
######## HELPER FOR PLOT 3-D
def plot_3d(name,X,Y,Z):
fig = plt.figure(name)
ax = fig.gca(projection='3d')
X = np.array(X)
Y = np.array(Y)
Z = np.array(Z)
ax.plot_wireframe(X,Y,Z,rstride=10,cstride=10)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
plt.show()
但我不知道如何转换数据 X、Y、Z 以使其满足 matplotlib 函数的要求,该函数需要 X、Y、Z 的二维列表。
对于第一张图,我阅读了帮助,想在 3d 中使用 2d 图。示例源代码给出:
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z')
其中 z 是常量坐标。在我的例子中,x 是常量坐标。我适应
fig = plt.figure('2d profiles')
ax = fig.gca(projection='3d')
for i in range(10):
x = pt ## this is a scalar
y = np.array(y)
z = np.array(z)
ax.plot(xs = x, y, z, xdir='x')
plt.show()
但有警告:关键字 arg 后有非关键字 arg。如何修复?
感谢和问候
请您参考如下方法:
关于在 3D 中显示一系列矢量,我提出了以下“几乎可行”的解决方案:
def visualizeSignals(self, imin, imax):
times = self.time[imin:imax]
nrows = (int)((times[(len(times)-1)] - times[0])/self.mod) + 1
fig = plt.figure('2d profiles')
ax = fig.gca(projection='3d')
for i in range(nrows-1):
x = self.mat1[i][0] + self.mod * i
y = np.array(self.mat1T[i])
z = np.array(self.mat2[i])
ax.plot(y, z, zs = x, zdir='z')
plt.show()
至于 2D 表面或网格图,我是通过使用网格来获得的。请注意,一旦您了解了网格网格的构建方式,您就可以自己复制网格网格。有关 meshgrid 的更多信息,请参阅 this post .
这是代码(不能这样使用它,因为它指的是类成员,但您可以基于我正在使用的 matplotlib 中的 3d 绘图方法构建您的代码)
def visualize(self, imin, imax, typ_ = "wireframe"):
"""
3d plot signal between imin and imax
. typ_: type of plot, "wireframce", "surface"
"""
times = self.retT[imin:imax]
nrows = (int)((times[(len(times)-1)] - times[0])/self.mod) + 1
self.modulate(imin, imax)
fig = plt.figure('3d view')
ax = fig.gca(projection='3d')
x = []
for i in range(nrows):
x.append(self.matRetT[i][0] + self.mod * i)
y = []
for i in range(len(self.matRetT[0])):
y.append(self.matRetT[0][i])
y = y[:-1]
X,Y = np.meshgrid(x,y)
z = [tuple(self.matGC2D[i]) for i in range(len(self.matGC))] # matGC a matrix
zzip = zip(*z)
for i in range(len(z)):
print len(z[i])
if(typ_ == "wireframe"):
ax.plot_wireframe(X,Y,zzip)
plt.show()
elif(typ_ == "contour"):
cset = ax.contour(X, Y, zzip, zdir='z', offset=0)
plt.show()
elif(typ_ == "surf_contours"):
surf = ax.plot_surface(X, Y, zzip, rstride=1, cstride=1, alpha=0.3)
cset = ax.contour(X, Y, zzip, zdir='z', offset=-40)
cset = ax.contour(X, Y, zzip, zdir='x', offset=-40)
cset = ax.contour(X, Y, zzip, zdir='y', offset=-40)
plt.show()
