✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

How to draw mesh surface in Plotly of which each face may have more than three vertices?

It’s indicated on 3D Mesh Plots in Python that go.Mesh3d draws a 3D set of triangles with vertices given by x , y and z..

May I ask how to draw mesh surface in Plotly of which each face may have more than three vertices?

@oat

If your polygons are all convex polygons, then you must triangulate them. The array of vertices is the same, but to polygons one associates the array of triangles:

 import numpy as np

polygons = [[0,2,7], [1,5,10,12], [6,8,4], [9, 7, 2, 4, 12]]

triangles =[]
for p in polygons:
    if len(p) <3:
        raise ValueError("each polygon must have len >=3")
    elif len(p) == 3:
        triangles.append(p)
    else:
        triangles.extend([[p[0], p[i], p[i+1]]  for i in range(1, len(p)-1)])
print(triangles)

[[0, 2, 7],
 [1, 5, 10],
 [1, 10, 12],
 [6, 8, 4],
 [9, 7, 2],
 [9, 2, 4],
 [9, 4, 12]]

Now you can use go.Mesh3d:

x, y, z = vertices.T
i, j, k = np.asarray(triangles).T
fig = go.Figure(go.Mesg3d(x=x, y=y, z=z,
                          i=i, j=j, k=k,
                          intensity=z,
                          colorscale="your_preferred_colorscale"))

Thanks, @empet

However, I didn’t quite get the example code, especially the polygons list of lists. May I ask what does it mean?

Plus, I got the error TypeError: ‘list’ object is not callable running the code for this line:

triangles.extend([[p[0], p[i], p[i+1]]  for i in range(1, len(p)-1)])

Appreciate your advice.

@oat You addressed the following question:

“May I ask how to draw mesh surface in Plotly of which each face may have more than three vertices ?”, but did not mention how many vertices have your faces. So I gave a general answer, when you have triangles, quadrangles, etc in your list of lists, that I caled naturally: polygons. Perhaps you expected to call it faces or otherwise, like in your un-specified code. I copied again the code I gave here and pasted in my notebook and it works.

I don’t understand why you get that error. The code is correct. If you want a solution for your usecase, please provide data.