How can an almost arbitrary plane in a 3D dataset be plotted by matplotlib?

前端 未结 5 1545
慢半拍i
慢半拍i 2021-01-18 15:11

There is an array containing 3D data of shape e.g. (64,64,64), how do you plot a plane given by a point and a normal (similar to hkl planes in crystallography), through this

5条回答
  •  情歌与酒
    2021-01-18 15:44

    For the reduced requirements, I prepared a simple example

    import numpy as np
    import pylab as plt
    
    data = np.arange((64**3))
    data.resize((64,64,64))
    
    def get_slice(volume, orientation, index):
        orientation2slicefunc = {
            "x" : lambda ar:ar[index,:,:], 
            "y" : lambda ar:ar[:,index,:],  
            "z" : lambda ar:ar[:,:,index]
        }
        return orientation2slicefunc[orientation](volume)
    
    plt.subplot(221)
    plt.imshow(get_slice(data, "x", 10), vmin=0, vmax=64**3)
    
    plt.subplot(222)
    plt.imshow(get_slice(data, "x", 39), vmin=0, vmax=64**3)
    
    plt.subplot(223)
    plt.imshow(get_slice(data, "y", 15), vmin=0, vmax=64**3)
    plt.subplot(224)
    plt.imshow(get_slice(data, "z", 25), vmin=0, vmax=64**3)  
    
    plt.show()  
    

    This leads to the following plot:

    Four example slices

    The main trick is dictionary mapping orienations to lambda-methods, which saves us from writing annoying if-then-else-blocks. Of course you can decide to give different names, e.g., numbers, for the orientations.

    Maybe this helps you.

    Thorsten

    P.S.: I didn't care about "IndexOutOfRange", for me it's o.k. to let this exception pop out since it is perfectly understandable in this context.

提交回复
热议问题