create an isosurface with Poly3DCollection

40 Views Asked by At

I have a matlab code which plots isourfaces. It works fine.

I have translated that code to python, and I am having some problems. I am using Poly3DCollection to create a surface, but it is not given me any isosurface, only a plot of the axes (this is the result that I get).

I should get something like this: result from matlab

import netCDF4
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from skimage import measure 
import trimesh
import matplotlib.pyplot as plt
import netCDF4 as nc



def isosurf(ncfile='mat_vec1000.cdf', afac=0.2):

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, projection='3d')
    
    with nc.Dataset(ncfile, 'r') as ncdata:
        x = ncdata.variables['x'][:]
        y = ncdata.variables['y'][:]
        z = ncdata.variables['z'][:]
        A = ncdata.variables['A'][:]
        
        
    # Extract the velocity components
    u = A[0, :, :, :]
    v = A[1, :, :, :]
    w = A[2, :, :, :]


    # Create a mesh grid
    X, Y, Z = np.meshgrid(x, y, z, indexing='ij')


    # # Compute the isosurface threshold
    amin = np.min(A)
    amax = np.max(A)
    aiso = (1 - afac) * amin + afac * amax
    
    
    # Compute isosurface
    verts, faces, _, _ = measure.marching_cubes(u, aiso)
    
    # Create a Poly3DCollection object for the surface
    mesh_poly = Poly3DCollection(verts[faces], alpha=0.01)
    mesh_poly.set_facecolor('r')
    mesh_poly.set_edgecolor('r')
    
    # Create figure and 3D axes
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, projection='3d')
    
    # Add the surface to the plot
    ax.add_collection3d(mesh_poly)
    
    # Show the plot
    plt.show()

 


if __name__ == '__main__':
    isosurf()

    plt.savefig('./Iso.png')


0

There are 0 best solutions below