Plotting a 3d data read from a file using mayavi

2019-08-06 02:50发布

问题:

I have a data file in the following format:

x y z f(x) f(y) f(z)

I want to plot it using contour3d of mayavi:

def fill_array(output_array,source_array,nx,ny,nz,position):
    for i in range(nx):
        for j in range(ny):
            for k in range(nz):
                output_array[i][j][k] = source_array[i][j][k][position]

nx = 8
ny = 8
nz = 8

ndim = 6

x = np.zeros((nx,ny,nz))
y = np.zeros((nx,ny,nz))
z = np.zeros((nx,ny,nz))
fx = np.zeros((nx,ny,nz))
fy = np.zeros((nx,ny,nz))
fz = np.zeros((nx,ny,nz))

data_file = np.loadtxt('datafile')
f = np.reshape(data_file, (nx,ny,nz,ndim))
fill_array(x,f,nx,ny,nz,0))
fill_array(y,f,nx,ny,nz,1)
fill_array(z,f,nx,ny,nz,2)
fill_array(fx,f,nx,ny,nz,3)
fill_array(fy,f,nx,ny,nz,4)
fill_array(fz,f,nx,ny,nz,5)

f2 = fx**2 + fy**2 + fz**2
plot_data = mlab.contour3d(f2)
mlab.colorbar(plot_data,title='f2',orientation='vertical')
mlab.savefig('f.png',magnification=5)

This was working fine when data is arranged in a order (x,y,z) grid data. But with file written not in order it is creates plot which doesn't match the one with ordered data (which I know is correct). What could be the reason/solution ?

Of course I only want to arrange x,y,z and then associate functional value f(x),f(y),f(z) to its right position (x,y,z).

回答1:

It worked.
I added the following just after reading the file (rest code remaining same):

data_file = np.loadtxt('datafile', 
dtype=[('x',float),('y',float),('z',float),('fx',float),('fy',float),('fz',float)])
data_file = np.sort(data_file,order=['z','y'])
f = np.array(data_file).reshape(nx,ny,nz)