在 Python 中绘制 3d 数组的最有效方法是什么? [英] What is the most efficient way to plot 3d array in Python?

查看:72
本文介绍了在 Python 中绘制 3d 数组的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中绘制 3d 数组的最有效方法是什么?

What is the most efficient way to plot 3d array in Python?

例如:

volume = np.random.rand(512, 512, 512)

其中数组项代表每个像素的灰度颜色.

where array items represent grayscale color of each pixel.

以下代码运行速度太慢:

The following code works too slow:

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')
volume = np.random.rand(20, 20, 20)
for x in range(len(volume[:, 0, 0])):
    for y in range(len(volume[0, :, 0])):
        for z in range(len(volume[0, 0, :])):
            ax.scatter(x, y, z, c = tuple([volume[x, y, z], volume[x, y, z], volume[x, y, z], 1]))
plt.show()

推荐答案

首先,一个 512x512x512 点的密集网格数据太多,无法绘制,不是从技术角度而是从观察时能够从中看到任何有用的东西剧情.您可能需要提取一些等值面,查看切片等.如果大多数点不可见,那么可能没问题,但是您应该要求 ax.scatter 仅显示要制作的非零点速度更快.

First, a dense grid of 512x512x512 points is way too much data to plot, not from a technical perspective but from being able to see anything useful from it when observing the plot. You probably need to extract some isosurfaces, look at slices, etc. If most of the points are invisible, then it's probably okay, but then you should ask ax.scatter to only show the nonzero points to make it faster.

也就是说,您可以通过以下方式更快地完成此操作.技巧是消除所有 Python 循环,包括那些会隐藏在像 itertools 这样的库中的循环.

That said, here's how you can do it much more quickly. The tricks are to eliminate all Python loops, including ones that would be hidden in libraries like itertools.

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

# Make this bigger to generate a dense grid.
N = 8

# Create some random data.
volume = np.random.rand(N, N, N)

# Create the x, y, and z coordinate arrays.  We use 
# numpy's broadcasting to do all the hard work for us.
# We could shorten this even more by using np.meshgrid.
x = np.arange(volume.shape[0])[:, None, None]
y = np.arange(volume.shape[1])[None, :, None]
z = np.arange(volume.shape[2])[None, None, :]
x, y, z = np.broadcast_arrays(x, y, z)

# Turn the volumetric data into an RGB array that's
# just grayscale.  There might be better ways to make
# ax.scatter happy.
c = np.tile(volume.ravel()[:, None], [1, 3])

# Do the plotting in a single call.
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(x.ravel(),
           y.ravel(),
           z.ravel(),
           c=c)

这篇关于在 Python 中绘制 3d 数组的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆