1. import matplotlib.pyplot as plt
    2. import numpy as np
    3. from mpl_toolkits.mplot3d import Axes3D
    4. # prepare some coordinates
    5. x, y, z = np.indices((16, 16, 16))
    6. # draw cuboids in the top left and bottom right corners, and a link between them
    7. #cube1 = (x < 230)& (x > 0) & (y < 200) & (y > 0) & (z < 170) & (z > 0)
    8. cube1 = (x > 3) & (x < 12) & (y > 4) & (y < 13) & (z > 5) & (z < 14)
    9. #cube2 = (x >= 5) & (y >= 5) & (z >= 5)
    10. #link = abs(x - y) + abs(y - z) + abs(z - x) <= 2
    11. # combine the objects into a single boolean array
    12. voxels = cube1 # | cube2 | link
    13. # set the colors of each object
    14. colors = np.empty(voxels.shape, dtype=object)
    15. #colors[link] = 'red'
    16. colors[cube1] = 1#"gray"#'blue'
    17. #colors[cube2] = 'green'
    18. colors = np.random.random((16, 16, 16, 3))
    19. # and plot everything
    20. fig = plt.figure(dpi=800)
    21. ax = Axes3D(fig) # 一个轴对象
    22. ax.grid()
    23. ax.text(-1, -1, -1, "(0, 0, 0)")
    24. ax.text(15, 15, 15, "(256, 256, 256)")
    25. ax.text(17, -1, -1, "(256, 0, 0)")
    26. ax.set_xlabel('X axis')
    27. ax.set_ylabel('Y axis')
    28. ax.set_zlabel('Z axis')
    29. ax.set_xticks([])
    30. ax.set_yticks([])
    31. ax.set_zticks([]) # 轴对象的设置标签方法
    32. ax.voxels(voxels, facecolors=colors, edgecolor='k')
    33. plt.savefig("3d.jpg")
    34. plt.show()

    绘制三维图 - 图1