python - 将 3D 切片绘制为热图

标签 python numpy matplotlib

如何在 python 上可视化 4d 数据,例如我有这样的数据:

x,y,z = np.mgrid[0:10:10j,20:50:30j,-10:5:15j]
t = np.random.random((10,30,15))

我想像这样可视化数据:

visualize on matlab

ps:我尝试在 matlab 上使用切片函数,如下所示

[x,y,z] = meshgrid(0:1:9,20:1:49,-10:1:4)
temp = rand(30,10,15);
xslice = 5;  %can add more slice
yslice = 35; 
zslice = 0;
slice(x, y, z, temp, xslice, yslice, zslice)

最佳答案

您可以使用plot_surfacethis answer 中提出的在这样的函数中:

import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Plot slices of the data at the given coordinates
def plot_slices(x, y, z, data, xslice, yslice, zslice, ax=None):
    if ax is None:
        ax = plt.figure().add_subplot(111, projection='3d')
    # Normalize data to [0, 1] range
    vmin, vmax = data.min(), data.max()
    data_n = (data - vmin) / (vmax - vmin)
    # Take slices interpolating to allow for arbitrary values
    data_x = scipy.interpolate.interp1d(x, data, axis=0)(xslice)
    data_y = scipy.interpolate.interp1d(y, data, axis=1)(yslice)
    data_z = scipy.interpolate.interp1d(z, data, axis=2)(zslice)
    # Pick color map
    cmap = plt.cm.plasma
    # Plot X slice
    xs, ys, zs = data.shape
    xplot = ax.plot_surface(xslice, y[:, np.newaxis], z[np.newaxis, :],
                            rstride=1, cstride=1, facecolors=cmap(data_x), shade=False)
    # Plot Y slice
    yplot = ax.plot_surface(x[:, np.newaxis], yslice, z[np.newaxis, :],
                            rstride=1, cstride=1, facecolors=cmap(data_y), shade=False)
    # Plot Z slice
    zplot = ax.plot_surface(x[:, np.newaxis], y[np.newaxis, :], np.atleast_2d(zslice),
                            rstride=1, cstride=1, facecolors=cmap(data_z), shade=False)
    return xplot, yplot, zplot

然后你可以像这样使用它:

import numpy as np

np.random.seed(0)
x = np.linspace(0, 10, 10)
y = np.linspace(20, 50, 30)
z = np.linspace(-10, 5, 15)
t = np.random.random((10, 30, 15))
ax = plt.figure().add_subplot(111, projection='3d')
plot_slices(x, y, z, t, 5, 35, 0, ax=ax)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

输出:

Data slices

不幸的是,Matplotlib 不能很好地处理相交的 3D 对象,并且剪切不正确,但这是另一种问题。

关于python - 将 3D 切片绘制为热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56688602/

相关文章:

python - 带有 asyncio 的 UDP 服务器

python - 将 cmd 命令的过滤输出存储在变量中

Python 调试器告诉我 Numpy 数组的值为 "*** Newest frame"

python - Cartopy 背景颜色(数据域之外)

python - 使用 MatPlotLib 的热力世界地图

python - 使用 Python 字典通过 Plotly Express 创建条形图

python - 如何在 peewee 查询的文本字段中搜索子字符串

python - 在 python 2.7 中将包含 datetime.timedelta 的 numpy 数组转换为秒的优雅方法

python - 使用 Sklearn 的 score 方法得到 ValueError : multiclass-multioutput is not supported

pandas - 在 Python 中生成词云来显示数字的频率