Plotting a surface contour for a given value in a 3D numpy matrix Plotting a surface contour for a given value in a 3D numpy matrix numpy numpy

Plotting a surface contour for a given value in a 3D numpy matrix


After a lot of digging around, I think I've arrived at a solution that works (for a sphere at least--will update my answer when I try out deformations of a sphere). Many thanks to the comments which helped me think down the right path. I am basically using a ConvexHull for the triangulation from scipy.spatial:

from matplotlib.tri import Triangulationfrom scipy.spatial import ConvexHulldef clean (A, t, dt):    # function for making A binary for t+-dt    # t is the target value I want in the matrix A with tolerance dt    new_A = np.copy(A)    new_A[np.logical_and(new_A > t-dt, new_A < t+dt)] = -1    new_A[new_A != -1] = 0    new_A[new_A == -1] = 1    return (new_A)def get_surface (X, Y, Z, new_A):    x_vals = []    y_vals = []    z_vals = []    # Retrieve (x,y,z) coordinates of surface    for i in range(new_A.shape[0]):        for j in range(new_A.shape[1]):            for k in range(new_A.shape[2]):                if new_A[i,j,k] == 1.0:                    x_vals.append(X[i,j,k])                    y_vals.append(Y[i,j,k])                    z_vals.append(Z[i,j,k])    return (np.array(x_vals), np.array(y_vals), np.array(z_vals))cleaned_A = clean (A, t=2.5, dt=0.001)x_f, y_f, z_f = get_surface (X, Y, Z, cleaned_A )Xs = np.vstack((x_f, y_f, z_f)).Thull = ConvexHull(Xs)x, y, z = Xs.Ttri = Triangulation(x, y, triangles=hull.simplices)fig = plt.figure()ax = fig.add_subplot(111, projection='3d', aspect='equal')ax.plot_trisurf(tri, z, color='g', alpha=0.1)