ValueError:无效RGBA参数.为什么会这样呢?我该怎么修理它?



我想创建一个简单的立方体如下代码:

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

# Create axis
axes = [5,5,5]
# Create Data
data = np.ones(axes, dtype=np.bool)
# Controll Tranperency
alpha = 0.9
# Control colour RGBA colour
colors = np.empty(axes + [4], dtype=np.float32)
colors[0] = [1, 0, 0, alpha] # red
colors[1] = [0, 1, 0, alpha] # green
colors[2] = [0, 0, 1, alpha] # blue
colors[3] = [1, 1, 0, alpha] # yellow
colors[4] = [1, 1, 1, alpha] # grey
# Plot figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Voxels are used for customizations of sizes, positions, and colors.
ax.voxels(data, facecolors=colors, edgecolors='grey')
plt.show()

效果很好。但是当我改变axes = [10, 10, 10]时,这里是代码:

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

# Create axis
axes = [10, 10, 10]
# Create Data
data = np.ones(axes, dtype=np.bool)
# Controll Tranperency
alpha = 0.9
# Control colour RGBA colour
colors = np.empty(axes + [4], dtype=np.float32)
colors[0] = [1, 0, 0, alpha] # red
colors[1] = [0, 1, 0, alpha] # green
colors[2] = [0, 0, 1, alpha] # blue
colors[3] = [1, 1, 0, alpha] # yellow
colors[4] = [1, 1, 1, alpha] # grey
# Plot figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Voxels are used for customizations of sizes, positions, and colors.
ax.voxels(data, facecolors=colors, edgecolors='grey')
plt.show()

有时工作,有时不工作,并抛出错误:ValueError: Invalid RGBA argument: 4.435719e+27。同样的错误,当我删除dtype在data = np.ones(axes, type=np.bool)。现在我无法调试Invalid RGBA argument,因为我不明白是什么导致了错误。我读了这篇文章,但似乎是关于无效形状的错误,而不是无效值。

为什么会出现这个错误?我该怎么修理它?非常感谢。

你得到这个错误是因为np.empty基本上是随机填充的数组(有时使用空内存空间,这就是为什么它有时会为你工作)。这不是axes = [5, 5, 5]的问题,因为当你分配颜色时,你正在填写适当的RGBA值,但是在更大的轴上,它也不会起作用。

查看当轴为[5, 5, 5]时打印colors的结果与使用[10, 10, 10]时不适合您的时间

修复:使用np.zeros代替np.empty,以确保零是你得到的缺失值:

axes = [10, 10, 10]
colors = np.zeros(axes + [4], dtype=np.float32)

最新更新