python - 绘制多面体的 3D 曲面

标签 python matplotlib

我正在尝试使用 Python 和 Matplotlib 渲染由

给出的多面体的 3D 表面

enter image description here

但是我的代码(如下所示)似乎没有正确绘制它。应该怎么做呢?

尝试失败:

enter image description here

%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)

最佳答案

这是一种解决方案:

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
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 surface of a cube

关于python - 绘制多面体的 3D 曲面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707384/

相关文章:

python - 在 Tensorflow/Keras 中获取对称矩阵的上三角最有效的方法是什么?

python - matplotlib 颜色条中的小刻度线

python - 我可以在matplotlib中显示没有科学计数法的图片像素值吗

python - matplotlib在哪里存储数据

python - re.rompile 返回 true 和 false,不允许使用符号

python - 通过 pip 需求文件更新分发

python - 在对数 pyplot 中同时使用 yticks 和 ylim

python - 切片 2d numpy 数组

javascript - 在 Django 模板中访问 Javascript 变量

Python ctypes 指向结构的指针作为标识符,无需成员访问