首页 > 编程笔记 > Python笔记 阅读:2

Matplotlib voxels()函数的用法(附带实例)

在指定位置绘制三维体元素(通常为六面体,六面体并非必须标准形状,六个面坐标可以指定)。Matplotlib 中提供了 ax3d.voxels() 函数实现绘制三维体。

ax3d.voxels() 函数的格式为:
ax3d.voxels(filled):在 filled 为 True 的位置绘制六面体。
ax3d.voxels(filled, facecolors=colors):在 filled 为 True 的位置绘制六面体,并设置颜色。

注意 facecolors 和 edgecolors 颜色列表,颜色个数必须和 filled 数组一样。filled 形状为(m,n,k)则颜色形状为(m,n,k,4)。

【实例】利用 ax3d.voxels() 函数绘制三维体。
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax3d = fig.add_subplot(121, projection='3d')
# filled 为 bool 类型数组,在 True 的元素下标位置绘制体元素
i, j, k = np.indices((3, 3, 3))
filled = (i == j) & (j == k)  # 3 行 3 列 3 层,对角线为 True
c = plt.get_cmap('RdBu')(np.linspace(0, 1, 27)).reshape(3, 3, 3, 4)
ax3d.voxels(filled)  # 在 filled 为 True 的位置绘制六面体
ax3d.voxels(filled, facecolors=c)  # 在 filled 为 True 的位置绘制六面体,并设置颜色
ax3d = fig.add_subplot(122, projection='3d')
plt.show()
运行程序,效果如下图所示:


图 1 三维体

相关文章