绘制三维切片作为热图

2024-06-24 12:46:30 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在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)

Tags: 数据函数可视化np切片slicerandomtemp
1条回答
网友
1楼 · 发布于 2024-06-24 12:46:30

您可以在这样的函数中使用this 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不能很好地处理相交的三维对象,剪裁也不正确,但这是另一种问题。你知道吗

相关问题 更多 >