简体   繁体   English

从 3D numpy 数组创建 3D 图

[英]Creating a 3D plot from a 3D numpy array

Ok, so I feel like there should be an easy way to create a 3-dimensional scatter plot using matplotlib.好的,所以我觉得应该有一种简单的方法来使用 matplotlib 创建 3 维散点图。 I have a 3D numpy array ( dset ) with 0's where I don't want a point and 1's where I do, basically to plot it now I have to step through three for: loops as such:我有一个 3D numpy 数组( dset ),其中 0 是我不想要点的地方,1 是我想要的地方,基本上是为了绘制它,现在我必须逐步执行三个for:循环:

for i in range(30):
    for x in range(60):
        for y in range(60):
            if dset[i, x, y] == 1:
                ax.scatter(x, y, -i, zdir='z', c= 'red')

Any suggestions on how I could accomplish this more efficiently?关于如何更有效地完成这项工作的任何建议? Any ideas would be greatly appreciated.任何想法将不胜感激。

If you have a dset like that, and you want to just get the 1 values, you could use nonzero , which "returns a tuple of arrays, one for each dimension of a , containing the indices of the non-zero elements in that dimension.".如果您有这样的dset ,并且只想获得1值,则可以使用nonzero ,它“返回一个数组元组,每个维度对应a数组,包含该维度中非零元素的索引.”。

For example, we can make a simple 3d array:例如,我们可以制作一个简单的 3d 数组:

>>> import numpy
>>> numpy.random.seed(29)
>>> d = numpy.random.randint(0, 2, size=(3,3,3))
>>> d
array([[[1, 1, 0],
        [1, 0, 0],
        [0, 1, 1]],

       [[0, 1, 1],
        [1, 0, 0],
        [0, 1, 1]],

       [[1, 1, 0],
        [0, 1, 0],
        [0, 0, 1]]])

and find where the nonzero elements are located:并找到非零元素所在的位置:

>>> d.nonzero()
(array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]), array([0, 0, 1, 2, 2, 0, 0, 1, 2, 2, 0, 0, 1, 2]), array([0, 1, 0, 1, 2, 1, 2, 0, 1, 2, 0, 1, 1, 2]))
>>> z,x,y = d.nonzero()

If we wanted a more complicated cut, we could have done something like (d > 3.4).nonzero() or something, as True has an integer value of 1 and counts as nonzero.如果我们想要更复杂的切割,我们可以做类似(d > 3.4).nonzero()事情,因为 True 的整数值为 1 并且计数为非零。

Finally, we plot:最后,我们绘制:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, -z, zdir='z', c= 'red')
plt.savefig("demo.png")

giving给予

演示 3d 图像

If you wanted to avoid using the nonzero option (for example, if you had a 3D numpy array whose values were supposed to be the color values of the data points), you could do what you do, but save some lines of code by using ndenumerate .如果你想避免使用nonzero选项(例如,如果你有一个 3D numpy 数组,它的值应该是数据点的颜色值),你可以做你所做的,但通过使用保存一些代码行ndenumerate

Your example might become:你的例子可能会变成:

for index, x in np.ndenumerate(dset):
    if x == 1:
        ax.scatter(*index, c = 'red')

I guess the point is just that you dont need to have nested for loops to iterate through multidimensional numpy arrays.我想重点只是您不需要嵌套 for 循环来遍历多维 numpy 数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM