Search code examples
pythonplotlyvisualizationplotly-python

Plot a triangle using its vertices and fill the shape in 3D space using plotly python


I am trying to plot a tringle using its three vertices and fill the shape in three-dimensional space. I followed the Plotly Mesh3d guidelines Plotly Mesh3d, utilizing the go.Mesh3D method, however the triangle is not appearing in the output.

Here is the minimum working example

import plotly.graph_objects as go
import numpy as np

x = np.array([50, 50, 50])
y = np.array([-10, 10,-10])
z = np.array([50, 50, 60])

fig = go.Figure()
fig.add_trace(go.Mesh3d(x=x, y=y, z=z,alphahull=5,opacity=0.4,color='cyan'))
fig.show()

It produces this figure with out the triangle enter image description here

I want a figure something like this enter image description here


Solution

  • Check https://plotly.com/python/3d-mesh/ it says,

    If only coordinates are given, an algorithm such as Delaunay triangulation is used to draw the triangles. Otherwise the triangles can be given using the i, j and k parameters (see examples below).

    which means in your case, the Delaunay triangulation algorithm has failed to draw the surface.

    So, you need to manually specify the triangle surfaces you want to paint out.

    import numpy as np
    
    x = np.array([50, 50, 50])
    y = np.array([-10, 10,-10])
    z = np.array([50, 50, 60])
    
    i = np.array([0])
    j = np.array([1])
    k = np.array([2])
    
    fig = go.Figure()
    fig.add_trace(go.Mesh3d(x=x, y=y, z=z, alphahull=5, opacity=0.4, color='cyan', i=i, j=j, k=k))
    fig.show()
    

    That means you want one trangle surface to be painted, whose vertices are: vertices[0], vertices[1], vertices[2] (which is [50,-10,50], [50,10,50], [50,-10,60])

    It gives you: enter image description here

    See: "Mesh Tetrahedron" from https://plotly.com/python/3d-mesh/

    Also, though I don't know how Delaunay triangulation algorithm works, it seems failure happens when the amount of vertices is too small.