美文网首页python热爱者
使用python绘制三维圆柱网格模型图——voxels函数的使用

使用python绘制三维圆柱网格模型图——voxels函数的使用

作者: AtonementQAQ | 来源:发表于2017-12-20 21:03 被阅读1632次

    最近接到老师的新任务——画一个XXX的三维模型图,和师兄交流后大概知道了要做什么,在师兄的建议下成功入了python的坑。

    然而网上查了很长时间才在matplotlib的example中找到了这种画圆柱网格的模型图的实例。

    实例

    import matplotlib.pyplot as plt
    import matplotlib.colors
    import numpy as np
    from mpl_toolkits.mplot3d import Axes3D
    
    
    def midpoints(x):
       sl = ()
       for i in range(x.ndim):
           x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0
           sl += np.index_exp[:]
       return x
    
    # prepare some coordinates, and attach rgb values to each
    r, theta, z = np.mgrid[0:1:11j, 0:np.pi*2:25j, -0.5:0.5:11j]
    x = r*np.cos(theta)
    y = r*np.sin(theta)
    
    rc, thetac, zc = midpoints(r), midpoints(theta), midpoints(z)
    
    # define a wobbly torus about [0.7, *, 0]
    sphere = (rc - 0.7)**2 + (zc + 0.2*np.cos(thetac*2))**2 < 0.2**2
    
    # combine the color components
    hsv = np.zeros(sphere.shape + (3,))
    hsv[..., 0] = thetac / (np.pi*2)
    hsv[..., 1] = rc
    hsv[..., 2] = zc + 0.5
    colors = matplotlib.colors.hsv_to_rgb(hsv)
    
    # and plot everything
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.voxels(x, y, z, sphere,
             facecolors=colors,
             edgecolors=np.clip(2*colors - 0.5, 0, 1),  # brighter
             linewidth=0.5)
    
    plt.show()
    

    对于我这种python小白来说(黑人问号???)
    但一看这效果图,嗯嗯就是它!!!


    效果图.png

    通过百度看了半天终于懂了这段代码是什么意思了。嗯,没错,除了voxels函数其他都没用。。。。更蛋疼的是竟然百度不到voxels的用法,这个时候help()命令可帮了大忙。

    voxels原版说明

        voxels(*args, **kwargs) method of matplotlib.axes._subplots.Axes3DSubplot instance
        ax.voxels([x, y, z,] /, filled, **kwargs)
    
        Plot a set of filled voxels
    
        All voxels are plotted as 1x1x1 cubes on the axis, with filled[0,0,0]
        placed with its lower corner at the origin. Occluded faces are not
        plotted.
    
        Call signatures::
    
            voxels(filled, facecolors=fc, edgecolors=ec, **kwargs)
            voxels(x, y, z, filled, facecolors=fc, edgecolors=ec, **kwargs)
    
        .. versionadded:: 2.1
    
        Parameters
        ----------
        filled : 3D np.array of bool
            A 3d array of values, with truthy values indicating which voxels
            to fill
    
        x, y, z : 3D np.array, optional
            The coordinates of the corners of the voxels. This should broadcast
            to a shape one larger in every dimension than the shape of `filled`.
            These can be used to plot non-cubic voxels.
    
            If not specified, defaults to increasing integers along each axis,
            like those returned by :func:`~numpy.indices`.
            As indicated by the ``/`` in the function signature, these arguments
            can only be passed positionally.
    
        facecolors, edgecolors : array_like, optional
            The color to draw the faces and edges of the voxels. Can only be
            passed as keyword arguments.
            This parameter can be:
    
              - A single color value, to color all voxels the same color. This
                can be either a string, or a 1D rgb/rgba array
              - ``None``, the default, to use a single color for the faces, and
                the style default for the edges.
              - A 3D ndarray of color names, with each item the color for the
                corresponding voxel. The size must match the voxels.
              - A 4D ndarray of rgb/rgba data, with the components along the
                last axis.
    
        **kwargs
            Additional keyword arguments to pass onto
            :func:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection`
    
        Returns
        -------
        faces : dict
            A dictionary indexed by coordinate, where ``faces[i,j,k]`` is a
            `Poly3DCollection` of the faces drawn for the voxel
            ``filled[i,j,k]``. If no faces were drawn for a given voxel, either
            because it was not asked to be drawn, or it is fully occluded, then
            ``(i,j,k) not in faces``.
    

    大概看了下,发现比较重要的参数就是x,y,z和filled。

    • filled参数
     filled : 3D np.array of bool
            A 3d array of values, with truthy values indicating which voxels
            to fill
    

    它是一个三维的布尔数组。
    注意:一定要是三维的!!!
    三个维度的长度分别是你的圆柱形网格在r,θ,z方向上的网格数。以上面的实例为例,实例里r方向有10个网格,θ方向有24个网格,z方向有10个网格,所以sphere是一个(10,24,10)的三维数组。

    z方向10个网格.png
    最后说一下filled数组的取值影响,filled取True,则表示该网格填充,取Flase则表示不填充。若将实例中的sphere改为全是True的数组,则结果如下图所示。
    sphere全是True.png
    • x,y,z参数
      每个参数也都是三维数组,这三个参数的定义可以保证你的网格不是正方体,将实例中的三个参数删除后结果如下。


      无xyz参数.png

    相关文章

      网友评论

        本文标题:使用python绘制三维圆柱网格模型图——voxels函数的使用

        本文链接:https://www.haomeiwen.com/subject/ersnwxtx.html