Home > other >  Given corners of a quadrilateral, Plot shaded quadrilateral in 3d using matplotlib
Given corners of a quadrilateral, Plot shaded quadrilateral in 3d using matplotlib

Time:01-28

I have 4 corners of a rectangle (like this).

all_corners[0] = [[16.9491164719, 17.8960237441, 0.0],
    [17.89665059755603, 27.22995253575736, 0.0],
    [16.9491164719, 17.8960237441, 2.552],
    [17.89665059755603, 27.22995253575736, 2.552]]

I need to plot this rectangle in a 3d space and I also need to plot multiple rectangles in a similar way. Is there any way to get this done? Also I need this to work for arbitrary shapes like quadrilateral, polygon but it's secondary for now, first I need to plot a shaded rectangle with given corner coordinates.

I tried Poly3dCollection, i'm getting weird traingles, not rectangles and many methods I found isn't what I want or I'm getting errors.

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)  
ax.add_collection3d(Poly3DCollection(all_corners[0]))
ax.set_ylim3d(10,40)
ax.set_xlim3d(10,40)
ax.set_zlim3d(0,4)
plt.show()

CodePudding user response:

You code is almost good. You only have two small mistakes:

  1. The vertices are connected in the order provided. You should pass them in the desired order. Otherwise, you will get a self-intersecting polygon.
  2. Poly3DCollection expects a list of array like objects where each item describes a polygon. This is useful if you want to add many polygons at once. Thus, you should not pass all_corners[0] but all_corners as the first parameter
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt

all_corners = []

all_corners.append([[16.9491164719, 17.8960237441, 0.0],
    [17.89665059755603, 27.22995253575736, 0.0],
    [17.89665059755603, 27.22995253575736, 2.552],  # note the permutation of
    [16.9491164719, 17.8960237441, 2.552],          # these two points
    ])

# You can add many polygons at once
all_corners.append([[10, 10, 0.0], [15, 15, 0.0], [15, 15, 2],
    [10, 10, 2]])

fig = plt.figure()
ax = Axes3D(fig)  
ax.add_collection3d(Poly3DCollection(all_corners)) # list of array-like
ax.set_ylim3d(10,40)
ax.set_xlim3d(10,40)
ax.set_zlim3d(0,4)
plt.show()
  •  Tags:  
  • Related