简体   繁体   中英

Plot a 3D Surface of a polyhedron

I'm attempting to use Python and Matplotlib to render a 3D surface of a polyhedron, given by

在此处输入图片说明

However my code (shown below) does not seem to draw it correctly. How should this be done instead?

Failed Attempt:

在此处输入图片说明

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter



delta = 0.1

def x_func(x):
    return abs(x)

def y_func(y):
    return abs(y)

def z_func(z):
    return abs(z)


x = np.arange(-1, 1, delta)
x1 = x_func(x)

y = np.arange(-1, 1, delta)
y1 = y_func(y)

X, Y = meshgrid(x1, y1)

z = np.arange(-1, 1, delta)
Z = z_func(z)

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ax.set_zlim([-1,1])
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.RdBu, linewidth=0.1)

Here's one solution:

import mpl_toolkits.mplot3d as a3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import scipy as sp
# Vertex data
verts= [    
      (-1, -1, -1), (-1, -1, 1), (-1, 1, 1), (-1, 1, -1),
      (1, -1, -1), (1, -1, 1), (1, 1, 1), (1, 1, -1)
        ]

# Face data
faces = np.array([ 
   [0, 1, 2, 3], [4, 5, 6, 7], [0, 3, 7, 4], [1, 2, 6, 5],     
   [0, 1, 5, 4], [2, 3, 7, 6]
   ])

ax = a3.Axes3D(plt.figure())
ax.dist=30
ax.azim=-140
ax.elev=20[enter image description here][1]
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ax.set_zlim([-1,1])

for i in np.arange(len(faces)):
    square=[ verts[faces[i,0]], verts[faces[i,1]], verts[faces[i, 2]], verts[faces[i, 3]]]
    face = a3.art3d.Poly3DCollection([square])
    face.set_color(colors.rgb2hex(sp.rand(3)))
    face.set_edgecolor('k')
    face.set_alpha(0.5)
    ax.add_collection3d(face)

plt.show()

The figure output is this: The surface of a cube

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM