python-3.x - ValueError : Invalid RGBA argument. 为什么会这样?我该如何修复它?

标签 python-3.x numpy matplotlib

我正在尝试按照以下代码创建一个简单的多维数据集:

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。当我删除 data = np.ones(axes, type=np.bool) 中的 dtype 时,出现同样的错误。现在我无法调试无效的 RGBA 参数,因为我不明白是什么导致了错误。我读过this ,但似乎是关于无效形状的错误,而不是无效值的错误。

为什么会发生这个错误?我该如何修复它?非常感谢。

最佳答案

您收到此错误是因为 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)

关于python-3.x - ValueError : Invalid RGBA argument. 为什么会这样?我该如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69052375/

相关文章:

python - 如何使用selenium点击discord服务器 channel ?

Python :Wave. 将帧读取到 numpy 数组以获取 fft

python - 如何附加到 numpy 数组而不将结果重新分配给新变量?

python - Numpy 将数组从 float 转换为字符串

python - 在 Python 中将列表中的值作为 pandas 数据框中的列值的可扩展方法

python - python 中的正则表达式匹配以换行符分隔的字符串

python - 从具有索引列表的多维数组中进行选择

python - 使用 SQLite 的 NumPy 数组

python - Pyplot 用图像(png 或 numpy 数组)而不是文本进行注释

python - 如何在matplotlib中绘制三次样条