How to fix matplotib incompatibility

Question:

I needed to visualize a cube and decided to use matplotib for python.

For some reason, code refuses to run properly. I tried out code from geeksforgeeks and matplotlib documentation example, neither works.

Is there a compatibility issue or I am doing something wrong?

For exaple this code (from geeksforgeeks):

# 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')

Outputs:

    C:UsersUserDesktopCube visualizationcube.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:UsersUserDesktopCube visualizationcube.py", line 10, in <module>
    data = np.ones(axes, dtype=np.bool)
                               ^^^^^^^
  File "C:UsersUserAppDataLocalProgramsPythonPython311Libsite-packagesnumpy__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

I am using the newest version for python and just istalled matplotib using python -m pip install -U matplotlib

Answers:

np.bool was deprecated long ago and recently removed in favor of the built-in bool, so just change np.bool with bool.

"tutorial" sites are almost always outdated as no one is revising them, so instead you should check the official documentation of matplotlib and numpy, such as cube documentation

you are also missing a plt.show() at the end of your code.

Answered By: Ahmed AEK

I’ve already upvoted Ahmed’s answer, but I cannot resist posting the resulting image.

enter image description here
that, of course, is obtained using data = np.ones(axes, dtype=bool) in place of data = np.ones(axes, dtype=np.bool) (and other tricks, irrelevant to the OP question).

Answered By: gboffi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.