Home > Net >  How to Calculate the Volume and Area Surface From the 3D Plot Using Matplotlib and Numpy?
How to Calculate the Volume and Area Surface From the 3D Plot Using Matplotlib and Numpy?

Time:01-23

Hi all I want to know how to calculate the volume and the surface area of this 3D plot?

I am using the right size for the width and length and height.

this is my code:

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# vertices of a prism
v = np.array([[-2, -2, -2.5], [2, -2, -2.5], [2, 2, -2.5],  [-2, 2, -2.5], [2,0,2.5], 
        [-2,0,2.5]])
ax.scatter3D(v[:, 0], v[:, 1], v[:, 2])

# generate list of sides' polygons of our prism
verts = [ [v[0],v[1],v[4],v[5]], [v[0],v[3],v[5]],
 [v[2],v[1],v[4]], [v[2],v[3],v[5],v[4]], [v[0],v[1],v[2],v[3]]]

# plot sides
ax.add_collection3d(Poly3DCollection(verts, 
 facecolors='cyan', linewidths=1, edgecolors='r', alpha=.25))

plt.show()

1

CodePudding user response:

Try adding this to your code

a=v[1]-v[0]
b=v[3]-v[0]
c=v[4]-v[1]

Volume=np.dot(a,np.cross(b,c))

surface_area=2* (abs(a[0]*b[1]*c[2])   abs(a[1]*b[2]*c[0])   abs(a[2]*b[0]*c[1]))


print(volume)
print(Surface_area)

CodePudding user response:

This is what I wanted and the code works thanks to @Ali Redha

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# vertices of a prism
v = np.array([[-5, -2, -2.5], [5, -2, -2.5], [5, 2, -2.5],  [-5, 2, -2.5], [5,0,2.5], 
        [-5,0,2.5]])
ax.scatter3D(v[:, 0], v[:, 1], v[:, 2])

# generate list of sides' polygons of our prism
verts = [ [v[0],v[1],v[4],v[5]], [v[0],v[3],v[5]],
 [v[2],v[1],v[4]], [v[2],v[3],v[5],v[4]], [v[0],v[1],v[2],v[3]]]

# plot sides
ax.add_collection3d(Poly3DCollection(verts, 
 facecolors='cyan', linewidths=1, edgecolors='r', alpha=.25))

# Calculate Volume and Surface Area
a=v[1]-v[0]
b=v[3]-v[0]
c=v[4]-v[1]

volume=np.dot(a,np.cross(b,c))

surface_area=2* (abs(a[0]*b[1]*c[2])   abs(a[1]*b[2]*c[0])   abs(a[2]*b[0]*c[1]))

# Annotation
ax.set_title("Prism")
ax.text(2,0,6.6,"Volume= {}".format(volume), size=10,
                           verticalalignment='center', rotation=270)
ax.text(2,0,7.2,"Surface Area = {}".format(surface_area), size=10,
                           verticalalignment='center', rotation=270)
plt.show()

1

  • Related