Search code examples
numpymatplotlibscatter-plotnumpy-ndarrayscatter3d

Plotting a 3-dimensional numpy array


I have a 3d numpy array with the shape (128,128,384). Let's call this array "S". This array only contains binary values either 0s or 1s. enter image description here

\now \i want to get a 3d plot of this array in such a way that \ I have a grid of indices (x,y,z) and for every entry of S when it is one \ I should get a point printed at the corresponding indices in the 3d grid. e.g. let's say I have 1 entry at S[120,50,36], so I should get a dot at that point in the grid.

So far I have tried many methods but have been able to implement one method that works which is extremely slow and hence useless in my case. that method is to iterate over the entire array and use a scatter plot. \here is a snippet of my code:

from numpy import np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
for i in range(0,128):
    for j in range(0,128):
        for k in range(0,384):
            if S[i,j,k]==1:
                ax.scatter(i,j,k,zdir='z', marker='o')

Please suggest to me any method which would be faster than this.

Also, please note that I am not trying to plot the entries in my array. The entries in my array are only a condition that tells me if I should plot corresponding to certain indices.

Thank you very much


Solution

  • You can use numpy.where.

    In your example, remove the for loops and just use:

    i, j, k = np.where(S==1)
    ax.scatter(i,j,k,zdir='z', marker='o')