0

How do I draw a rectangle in 3D ? The code below works but it draws a triangle

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [0,1,1,0]
y = [0,0,1,1]
z = [0,1,0,1]
verts = [list(zip(x,y,z))]
ax.add_collection3d(Poly3DCollection(verts))
plt.show()

I tried adding a 4th corner but I get an error

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [0,1,1,0]
y = [0,0,1,1]
z = [0,1,0,1]
a = [0,1,0,1]
verts = [list(zip(x,y,z,a))]
ax.add_collection3d(Poly3DCollection(verts))
plt.show()

Is there a function that accepts 4 3D-coordinates then draws a flat rectangle? e.g.

ax.draw_rectangle3d(tl=[0,0,0],tr=[0,0,1],bl=[0,1,0],br=[0,1,1])

This function Adding a Rectangle Patch and Text Patch to 3D Collection in Matplotlib draws a flat rectangle but it does not allow me to set my own x,y,z coordinate and the rectangle is projected onto the axes.

Kong
  • 1,984
  • 8
  • 22
  • 45

1 Answers1

1

The Z axis is wrong should be [0,0,0,0], since each column is a point and the rectangle is on the 0 on Z axis.

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [0,1,1,0]
y = [0,0,1,1]
z = [0,0,0,0]
verts = [list(zip(x,y,z))]
ax.add_collection3d(Poly3DCollection(verts))
plt.show()

You can use this to plot multiple surfaces.

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt


fig = plt.figure()
ax = Axes3D(fig)

x = [0,1,1,0],[0,1,1,0]
y = [0,0,1,1],[0,0,1,1]
z = [0,0,0,0],[1,1,1,1]

surfaces = []

for i in range(len(x)):
    surfaces.append( [list(zip(x[i],y[i],z[i]))] )

for surface in surfaces:
    ax.add_collection3d(Poly3DCollection(surface))

plt.show()
Raynan
  • 11
  • 2