You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Matplotlib代码运行中的NumPy兼容性报错?

Matplotlib可视化立方体报错解决方法

问题情况

想用Python的Matplotlib库实现立方体可视化,但运行GeeksforGeeks及Matplotlib官方文档的示例代码均失败。使用最新版Python,且刚通过python -m pip install -U matplotlib完成Matplotlib的更新。

原示例代码

# Import libraries
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)

# Control Transparency
alpha = 0.9

# Control 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 is used to customizations of
# the sizes, positions and colors.
ax.voxels(data, facecolors=colors, edgecolors='grey')

运行报错信息

C:\Users\User\Desktop\Cube visualization\cube.py:10: FutureWarning: In the future `np.bool` will be defined as the corresponding NumPy scalar.  (This may have returned Python scalars in past versions.
  data = np.ones(axes, dtype=np.bool)
Traceback (most recent call last):
  File "C:\Users\User\Desktop\Cube visualization\cube.py", line 10, in <module>
    data = np.ones(axes, dtype=np.bool)
                               ^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\numpy\__init__.py", line 284, in __getattr__
    raise AttributeError("module {!r} has no attribute "
AttributeError: module 'numpy' has no attribute 'bool'. Did you mean: 'bool_'?

Process finished with exit code 1

错误原因

这是NumPy版本兼容性问题。新版NumPy已移除np.bool属性,替代方案是使用np.bool_,或者直接使用Python原生的bool类型。

修复后的代码

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

# Create axis
axes = [5, 5, 5]

# Create Data - 替换np.bool为np.bool_或Python原生bool
data = np.ones(axes, dtype=np.bool_)
# 也可以写成:data = np.ones(axes, dtype=bool)

# Control Transparency
alpha = 0.9

# Control 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 is used to customizations of
# the sizes, positions and colors.
ax.voxels(data, facecolors=colors, edgecolors='grey')
plt.show()  # 补充该行以弹出图形窗口

额外说明

原代码缺少plt.show()调用,即使代码无报错也不会显示图形窗口,修复时建议添加这一行。

内容的提问来源于stack exchange,提问作者zаѓатhᵾѕтѓа

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:32:31