Create 3D Voxel Plots with RGB

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to create a 3D voxel plot with RGB colors using Matplotlib. Voxel plots are a way of representing 3D data on a 2D plot by using cubes to represent the data points. The RGB colors will be used to represent the different values of the data.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} matplotlib/importing_matplotlib -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} matplotlib/figures_axes -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/variables_data_types -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/for_loops -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/lists -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/tuples -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/function_definition -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/importing_modules -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/data_collections -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/numerical_computing -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/data_visualization -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} python/build_in_functions -.-> lab-49026{{"`Create 3D Voxel Plots with RGB`"}} end

Importing Libraries

Before creating the plot, we need to import the required libraries. In this case, we will be using Matplotlib and NumPy.

import matplotlib.pyplot as plt
import numpy as np

Defining the Coordinates and Colors

Next, we need to define the coordinates and colors for the plot. In this example, we will use the np.indices function to create a 17x17x17 grid of values for the RGB colors.

r, g, b = np.indices((17, 17, 17)) / 16.0

We will also define a function midpoints to find the midpoints between the values in the grid. This will be used later to create the sphere.

def midpoints(x):
    sl = ()
    for _ in range(x.ndim):
        x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0
        sl += np.index_exp[:]
    return x

Creating the Sphere

We will now create a sphere in the plot by defining a condition for the RGB values that lie within a certain distance from the center of the plot.

rc = midpoints(r)
gc = midpoints(g)
bc = midpoints(b)

sphere = (rc - 0.5)**2 + (gc - 0.5)**2 + (bc - 0.5)**2 < 0.5**2

Combining the Colors

We will now combine the RGB color components into a single array of shape (17, 17, 17, 3).

colors = np.zeros(sphere.shape + (3,))
colors[..., 0] = rc
colors[..., 1] = gc
colors[..., 2] = bc

Plotting the Voxel Plot

Finally, we can plot the voxel plot using the ax.voxels function. We will pass in the RGB values, the condition for the sphere, the face colors, edge colors, and linewidth.

ax = plt.figure().add_subplot(projection='3d')
ax.voxels(r, g, b, sphere,
          facecolors=colors,
          edgecolors=np.clip(2*colors - 0.5, 0, 1),  ## brighter
          linewidth=0.5)
ax.set(xlabel='r', ylabel='g', zlabel='b')
ax.set_aspect('equal')
plt.show()

Summary

In this lab, we learned how to create a 3D voxel plot with RGB colors using Matplotlib. We imported the required libraries, defined the coordinates and colors, created a sphere, combined the colors, and plotted the voxel plot. Voxel plots are a useful way to represent 3D data on a 2D plot, and can be customized with different colors and shapes to represent different types of data.

Other Python Tutorials you may like