从3D numpy数组创建3D图 [英] Creating a 3D plot from a 3D numpy array
问题描述
好的,所以我觉得应该有一种简单的方法来使用matplotlib创建三维散点图.我有一个3D numpy数组(dset
),其中0是我不想要的点,而1是我想要的点,基本上要绘制它,现在我必须逐步执行以下三个for:
循环:
Ok, so I feel like there should be an easy way to create a 3-dimensional scatter plot using matplotlib. 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:
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.
推荐答案
如果您具有这样的dset
,并且只想获取1
值,则可以使用nonzero
,它返回一个数组的元组,每个维度对应a
,其中包含该维度中非零元素的索引.".
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.".
例如,我们可以制作一个简单的3d数组:
For example, we can make a simple 3d array:
>>> 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()
如果我们想要更复杂的切割,我们可以做类似(d > 3.4).nonzero()
之类的事情,因为True的整数值为1,并且算作非零.
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.
最后,我们绘制:
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")
给予
这篇关于从3D numpy数组创建3D图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!