1

How can I visualize 4d data on python, for example i have data like this :

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

and i want to visualize the data like this :

visualize on matlab

ps : i have try to use slice function on matlab like this

[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)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Wahyu Hadinoto
  • 198
  • 1
  • 10

1 Answers1

1

You can use plot_surface as proposed in this answer in a function like this:

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

You would then use it like this:

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')

Output:

Data slices

Unfortunately, Matplotlib doesn't handle intersecting 3D objects well and clipping is incorrect, but that is a different kind of issue.

jdehesa
  • 58,456
  • 7
  • 77
  • 121
  • For more consistent 3D plotting in Python, you may consider other libraries like [Mayavi](https://docs.enthought.com/mayavi/mayavi/). – jdehesa Jun 20 '19 at 16:45