Search code examples
pythonplotlygeometry-surface

how to draw multiple squares at different heights in plotly 3D


I am trying to draw area 1 squares that are parallel to xy-plane on different heights in plotly 3D. I can do it for points, which is basically scattering, and the code looks like this:

A=np.array([[213,254,245,217,198],[245,201,211,249,200],[211,189,32,212,227],[250,234,217,243,188],[222,243,212,209,199]])
points={}
for i in range(5):
    for j in range(5):
        points[i*5+j]={'x':i,'y':j,'z':A[i][j]}


data=pd.DataFrame(points)
data1=pd.DataFrame.transpose(data)
fig = px.scatter_3d(data1,x='x', y='y', z='z')
fig.show()

enter image description here

I also can draw line segments that are parallel to xy-plane at different heights:

enter image description here

These are the 0-skeleton and 1-skeleton of the matrix A. Now I need to draw the 2 skeleton which is multiple squares at different heights. I tried to use go.Surface but these surfaces covers the whole space and they intersect with each other. What I need is area 1 patches that are discrete whose projection is the matrix A or in grayscale it looks like this: enter image description here


Solution

  • You can add many little square surfaces, like this:

    import plotly.graph_objects as go
    
    def add_hovering_square(fig, x0, y0, size, height):
        fig.add_trace(go.Surface(
            z=[[height,height],[height,height]],
            x=[x0,x0+size], y=[y0,y0+size],
            coloraxis='coloraxis1'
        ))
    
    fig = go.Figure()
    
    add_hovering_square(fig, 1, 1, 1, 1)
    add_hovering_square(fig, 1, 2, 1, 2)
    add_hovering_square(fig, 2, 1, 1, 3)
    add_hovering_square(fig, 2, 2, 1, 4)
    
    fig.show()
    

    enter image description here