我有一个3D numpy数组,其尺寸为1400x1400x29。但是,数据是4D的,因为每个x,y,z都有一个不同的值(第4维)。我相信可以做到以下类似的事情。
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
//some calculation that creates a 3D array called "cube"
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for x in range(1400):
for y in range(1400):
for z in range(29):
ax.scatter(x, y, z, c=cube[x,y,z])
plt.show()
但是,以上脚本给我一个错误提示 “ TypeError:类型为'numpy.float64'的对象没有len()”
编辑1 完整的错误消息
File "cube.py", line 57, in <module>
ax.scatter(x, y, z, c=cube[z , x , y], cmap=plt.hot())
File "/pawsey/cle60up05/python/2.7.14/matplotlib/2.1.0/lib/python2.7/site-packages/matplotlib-2.1.0-py2.7-linux-x86_64.egg/mpl_toolkits/mplot3d/axes3d.py", line 2353, in scatter
xs, ys, s=s, c=c, *args, **kwargs)
File "/pawsey/cle60up05/python/2.7.14/matplotlib/2.1.0/lib/python2.7/site-packages/matplotlib-2.1.0-py2.7-linux-x86_64.egg/matplotlib/__init__.py", line 1710, in inner
return func(ax, *args, **kwargs)
File "/pawsey/cle60up05/python/2.7.14/matplotlib/2.1.0/lib/python2.7/site-packages/matplotlib-2.1.0-py2.7-linux-x86_64.egg/matplotlib/axes/_axes.py", line 4050, in scatter
colors = mcolors.to_rgba_array(c)
File "/pawsey/cle60up05/python/2.7.14/matplotlib/2.1.0/lib/python2.7/site-packages/matplotlib-2.1.0-py2.7-linux-x86_64.egg/matplotlib/colors.py", line 231, in to_rgba_array
result = np.empty((len(c), 4), float)
TypeError: object of type 'numpy.float64' has no len()
谢谢
答案 0 :(得分:0)
因此,了解cube
是形状为numpy.ndarray
的{{1}}时,绘制3D散点的正确方法是:
(1400, 1400, 29)
您必须使用数组而不是标量调用import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
//some calculation that creates a 3D array called "cube"
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = np.mgrid[:1400, :1400, :29]
ax.scatter(X, Y, Z, c=cube.ravel())
plt.show()
。另外,它需要一个1D数组作为ax.scatter
的输入,所以我叫c
。 ravel()
只是创建N维均匀网格的一种快速方法。它等效于np.mgrid
中的np.meshgrid
。如果您想了解更多信息,建议您阅读每个文档。