How to Draw 3D Cube using Matplotlib in Python?
Last Updated :
25 Jul, 2022
In this article, we will deal with the 3d plots of cubes using matplotlib and Numpy. Cubes are one of the most basic of 3D shapes. A cube is a 3-dimensional solid object bounded by 6 identical square faces. The cube has 6-faces, 12-edges, and 8-corners. All faces are squares of the same size. The total surface area of a cube is the sum of the area of the 6 identical squares.
Matplotlib comes with a wide variety of plots. Graphs help to understand trends, patterns to make correlations. Matplotlib was introduced for two-dimensional plotting. The 3d plot is enabled by importing the mplot3d toolkit., which comes with your standard Matplotlib. After importing, 3D plots can be created by passing the keyword projection="3d" to any of the regular axes creation functions in Matplotlib.
Modules Needed
- Matplotlib: It is a plotting library for Python programming it serves as a visualization utility library, Matplotlib is built on NumPy arrays, and designed to work with the broader SciPy stack.
- Numpy: It is a general-purpose array-processing package. It provides a high-performance multidimensional array and matrices along with a large collection of high-level mathematical functions.
- mpl_toolkits: It provides some basic 3d plotting (scatter, surf, line, mesh) tools. It is a collection of helper classes for displaying 3d axes in Matplotlib.
Approach
Step 1: Import libraries.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
Step 2: In this step, we are selecting the 3D axis of the dimension X =5, Y=5, Z=5, and in np.ones() we are passing the dimensions of the cube.
# Create axis
axes = [5, 5, 5]
# Create Data
data = np.ones(axes)
Step 3: In this step, we are selecting color opacity as alpha = 0.9 ( vary from 0.0 - 1.0 ). In the next step, we are passing the dimension of axes( i.e 5, 5, 5) + number of faces for the cube ( i.e 0-4 ) in np.empty() function after that we are passing color combination and opacity for each face of the cube.
# control Transparency
alpha = 0.9
# control colour
colors = np.empty(axes + [4])
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
Step 4: In this step, we used figure() function of the matplotlib library which is used to create a new figure, After that, we used add_subplot() method to add an Axes to the figure as 3-Dimensional(i.e Projection = '3d') part of a subplot arrangement. It has 3 arguments.
- The number of rows in the grid,
- The number of columns in the grid and,
- The position at which the new subplot must be placed.
It is to be noted that fig.add_subplot(1, 1, 1) is equivalent to fig.add_subplot(111).
# Plot figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
Step 5: And in this last step Voxels is used for customizations of the size, position, and grid color. The proper syntax is provided above.
# Voxels is used to customizations of the
# sizes, positions and colors.
ax.voxels(data, facecolors=colors, edgecolors='grey')
Example 1: Simple cube of one color.
Here changing colors[ : ], means we are selecting all the array elements as one color (i.e red) and to remove the grid we deleted 'edgecolor' parameter from voxels method to have simply one color cube.
Python3
# 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[:] = [1, 0, 0, alpha] # red
# 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)
Output:

Example 2:
Cube with Grid and different color
Python3
# 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')
Output:

Example 3: Faced cube along Y - axes
In this example, we will add one more line of code view_init( ) to change the axis view as we want. The view_init() can be used to change the axes view programmatically. Here we are using elev=100 and  azim=0.
Syntax: view_init(elev, azim)
Parameters: Â
- ‘elev’ stores the elevation angle in the z plane.
- ‘azim’ stores the azimuth angle in the x,y plane.
Python3
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
axes = [5, 5, 5]
data = np.ones(axes, dtype=np.bool)
colors = np.empty(axes + [4], dtype=np.float32)
# Control Transparency
alpha = .7
# Control colors
colors[0] = [1, 0, 0, alpha]
colors[1] = [0, 1, 0, alpha]
colors[2] = [0, 0, 1, alpha]
colors[3] = [1, 1, 0, alpha]
colors[4] = [0, 1, 1, alpha]
# set all internal colors to
# black with alpha=1
colors[1:-1, 1:-1, 1:-1, 0:3] = 0
colors[1:-1, 1:-1, 1:-1, 3] = 1
# Plot figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Control number of slice
data[-1] = True
data[-2] = False
data[-3] = False
data[-4] = False
data[-5] = True
# Voxels is used to customizations of
# the sizes, positions and colors.
ax.voxels(data, facecolors=colors, edgecolors='pink')
# it can be used to change the axes view
ax.view_init(100, 0)
Output:

Example 4: Faced cube along X-axes
The view_init() can be used to change the axes view programmatically. Here we are using elev=100 and  azim=90.
Python3
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
axes = [5, 5, 5]
data = np.ones(axes, dtype=np.bool)
colors = np.empty(axes + [4], dtype=np.float32)
# Control Transparency
alpha = .7
# Control colors
colors[0] = [1, 0, 0, alpha]
colors[1] = [0, 1, 0, alpha]
colors[2] = [0, 0, 1, alpha]
colors[3] = [1, 1, 0, alpha]
colors[4] = [0, 1, 1, alpha]
# set all internal colors to
# black with alpha=1
colors[1:-1, 1:-1, 1:-1, 0:3] = 0
colors[1:-1, 1:-1, 1:-1, 3] = 1
# Plot figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Control number of slice
data[-1] = 1
data[-2] = False
data[-3] = False
data[-4] = False
data[-5] = True
# Voxels is used to customizations
# of the sizes, positions and colors.
ax.voxels(data, facecolors=colors, edgecolors='pink')
# it can be used to change the axes view
ax.view_init(100, 90)
Output:

Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read