VOXELS

Excel Usage

=VOXELS(data, shape, title, edge_color)
  • data (list[list], required): Flattened 3D grid of boolean values (0 or 1).
  • shape (str, required): Shape of the 3D grid as ‘depth,height,width’ (e.g., ‘8,8,8’).
  • title (str, optional, default: null): Chart title.
  • edge_color (str, optional, default: “black”): Color of the voxel edges.

Returns (object): Matplotlib Figure object (standard Python) or base64 encoded PNG string (Pyodide).

Example 1: Simple 3x3x3 cube corners

Inputs:

data shape title
1 0 0 3,1,3 Voxel Corners
0 0 0
0 0 1

Excel formula:

=VOXELS({1,0,0;0,0,0;0,0,1}, "3,1,3", "Voxel Corners")

Expected output:

"chart"

Example 2: Single voxel

Inputs:

data shape
1 1,1,1

Excel formula:

=VOXELS({1}, "1,1,1")

Expected output:

"chart"

Example 3: Voxels with gray edges

Inputs:

data shape edge_color
1 1 2,1,2 gray
1 1

Excel formula:

=VOXELS({1,1;1,1}, "2,1,2", "gray")

Expected output:

"chart"

Example 4: Voxels without edges

Inputs:

data shape edge_color
1 0 2,1,2 none
0 1

Excel formula:

=VOXELS({1,0;0,1}, "2,1,2", "none")

Expected output:

"chart"

Python Code

import sys
import matplotlib
IS_PYODIDE = sys.platform == "emscripten"
if IS_PYODIDE:
    matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import io
import base64
import numpy as np

def voxels(data, shape, title=None, edge_color='black'):
    """
    Create a 3D voxel plot from a 3D grid of values.

    See: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.voxels.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        data (list[list]): Flattened 3D grid of boolean values (0 or 1).
        shape (str): Shape of the 3D grid as 'depth,height,width' (e.g., '8,8,8').
        title (str, optional): Chart title. Default is None.
        edge_color (str, optional): Color of the voxel edges. Valid options: Black, Gray, White, None. Default is 'black'.

    Returns:
        object: Matplotlib Figure object (standard Python) or base64 encoded PNG string (Pyodide).
    """
    def to2d(x):
        return [[x]] if not isinstance(x, list) else x

    try:
        data = to2d(data)
        if not isinstance(data, list) or not data or not isinstance(data[0], list):
            return "Error: Input data must be a 2D list (flattened grid)."

        # Prepare boolean array
        flat = []
        for row in data:
            for x in row:
                try:
                    if x is None or x == "":
                        flat.append(False)
                    else:
                        flat.append(bool(float(x)))
                except (TypeError, ValueError):
                    flat.append(False)

        # Parse shape
        try:
            d, h, w = map(int, shape.split(','))
        except Exception:
            return "Error: Invalid shape format. Use 'depth,height,width' (e.g., '8,8,8')."

        if len(flat) < d * h * w:
            return f"Error: Input data size ({len(flat)}) is smaller than requested shape {shape} ({d*h*w})."

        # Reshape
        voxel_array = np.array(flat[:d*h*w]).reshape((d, h, w))

        # Create figure with 3D projection
        fig, ax = plt.subplots(figsize=(10, 7), subplot_kw={"projection": "3d"})

        # Plot voxels
        ax.voxels(voxel_array, edgecolor=edge_color if edge_color != "none" else None)

        # Set title
        if title:
            ax.set_title(title)

        # Remove ticks for gallery style
        ax.set(xticklabels=[], yticklabels=[], zticklabels=[])

        if IS_PYODIDE:
            buf = io.BytesIO()
            plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
            plt.close(fig)
            buf.seek(0)
            img_bytes = buf.read()
            img_b64 = base64.b64encode(img_bytes).decode('utf-8')
            return f"data:image/png;base64,{img_b64}"
        else:
            return fig
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

Flattened 3D grid of boolean values (0 or 1).
Shape of the 3D grid as 'depth,height,width' (e.g., '8,8,8').
Chart title.
Color of the voxel edges.