Python 如何在3D图中绘制多维数组
问题描述
我有一个多维数组(P x N x M),我想以一种方式将每个N x M数组绘制在一个3D图中,使得P个图像沿着z轴叠放。
你知道如何在Python中做到这一点吗?
解决方案
如果你想将N x M数组作为“热图”沿着z轴叠放,这是一种方法:
import numpy as np
import matplotlib.pyplot as plt
# Generate some dummy arrays
P, N, M = 5, 10, 10
data = np.random.rand(P, N, M)
# Create a 3D figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Create meshgrid for x, y values
x, y = np.meshgrid(np.arange(M), np.arange(N))
# Plot each N x M array as a heatmap at different heights along the z-axis
for p in range(P):
heatmap = data[p]
ax.plot_surface(x, y, np.full_like(heatmap, p), facecolors=plt.cm.viridis(heatmap), rstride=1, cstride=1, antialiased=True, shade=False)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('P')
ax.set_title('Stacked Heatmaps')
plt.show()
结果: