matplotlib 如何在3D图中绘制多维数组

z9smfwbn  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(98)

我有一个多维数组(P x N x M),我想在一个3D图中绘制每个N x M数组,以使P图像沿着z轴堆叠。
你知道如何在Python中做到这一点吗?

dw1jzc5e

dw1jzc5e1#

如果你想让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()

结果:

qlfbtfca

qlfbtfca2#

您可以使用Matplotlib的Axes3D模块来实现这一点。此代码将生成一个3D散点图,其中来自P x N x M数组的每个2D切片沿z轴以不同的高度(由z变量控制)沿着。散点图中每个点的颜色表示相应切片中的值,并添加一个颜色条来指示数据值。

import numpy as np
import matplotlib.pyplot as plt

# Example multidimensional array of shape (P, N, M)
# Replace this with your actual data
P, N, M = 5, 10, 10
data = np.random.rand(P, N, M)

# Create a 3D scatter plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Create a meshgrid for the x and y values
x, y = np.meshgrid(range(N), range(M))

for p in range(P):
  # Flatten the 2D slice and stack it at the height of p
  z = np.full((N, M), p)
  ax.scatter(x, y, z, c=data[p].ravel(), cmap='viridis')

# Set labels for each axis
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# Customize the colorbar
norm = plt.Normalize(data.min(), data.max())
sm = plt.cm.ScalarMappable(cmap='viridis', norm=norm)
sm.set_array([])
fig.colorbar(sm, label='Data Values')

plt.show()

结果:

相关问题