Plot of 3D matrix with colour scale - Python
Question: I would like to plot a 3D matrix - essentially a box of numbers, each labelled
by an `x, y, z` triad of coordinates- by assigning a different colour to each
of the `x, y, z` point, according to its magnitude (for example, bigger
numbers in red and smaller numbers in blue). I cannot plot sections of the
matrix, I rather need to plot the whole matrix together.

If we call `matrix3D` my matrix, its elements are built this way:

    
    
    matrix3D[x][y][z] = np.exp(-(x**2+y**2+z**2))
    

How can I obtain the desired plot?

EDIT: Using Mayavi2 Contour3D(), I have tried to write the following:

    
    
    from mayavi import mlab
    
    X = np.arange(0, n_x, 1)
    Y = np.arange(0, n_z, 1)
    Z = np.arange(0, n_z, 1)
    X, Y, Z = np.meshgrid(X, Y, Z)
    obj = mlab.contour3d(X, Y, Z, matrix3D, contours=4, transparent=True)
    

where `n_x, n_y, n_z` are the dimension of the 3 axes. How can I actually see
and/or save the image now?


Answer: If you need to plot the whole thing I think you're best taking a look at
[mayavi](http://docs.enthought.com/mayavi/mayavi/mlab.html). This will let you
plot a volume and you should be able to get the results you need.

I know you said you need to plot the whole thing at once, but this might still
be of _some_ use. You can use `countourf` to plot like this:

    
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    matrix3D = np.empty((10, 10, 10))
    x = np.arange(10)
    y = np.arange(10)
    z = np.arange(10)
    matrix3D[x][y][z] = np.exp(-(x**2+y**2+z**2))
    
    fig = plt.figure()
    ax = fig.add_subplot(plt.subplot(1, 1, 1))
    ax.contourf(x, y, matrix3D[:, :, 3])
    
    plt.show()
    

This gives you a _slice_ of the 3D matrix (in this example the 4th slice).

[![enter image description
here](http://i.stack.imgur.com/8yM6E.png)](http://i.stack.imgur.com/8yM6E.png)

