【问题标题】:Plotting a 4D numpy data using matplotlib使用 matplotlib 绘制 4D numpy 数据
【发布时间】:2019-02-25 10:08:55
【问题描述】:

我有一个尺寸为 1400x1400x29 的 3D numpy 数组。但是,数据是 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()

谢谢

【问题讨论】:

  • 请添加完整的错误信息。
  • @DYZ 我已经用完整的错误信息编辑了问题
  • 什么代码cube 做什么?也许也添加该代码

标签: python numpy matplotlib plot


【解决方案1】:

所以理解cube 是形状为(1400, 1400, 29)numpy.ndarray,绘制3D 散点图的正确方法是:

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()

您必须使用数组而不是标量调用 ax.scatter。此外,它需要一个一维数组作为c 输入,所以我调用了ravel()np.mgrid 只是一种创建 N 维统一网格的快速方法。它相当于np.arangenp.meshgrid。如果您想了解更多信息,我建议您阅读每个文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2016-06-06
    • 1970-01-01
    • 2012-07-07
    • 2022-01-27
    • 1970-01-01
    相关资源
    最近更新 更多