CLUSTER_MAP

Excel Usage

=CLUSTER_MAP(data, title, color_map, colorbar)
  • data (list[list], required): Input matrix data.
  • title (str, optional, default: null): Chart title.
  • color_map (str, optional, default: “viridis”): Color map.
  • colorbar (str, optional, default: “true”): Show colorbar.

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

Examples

Example 1: Basic clustered heatmap

Inputs:

data
1 2 3
4 5 6
7 8 9
2 3 4

Excel formula:

=CLUSTER_MAP({1,2,3;4,5,6;7,8,9;2,3,4})

Expected output:

"chart"

Example 2: Cluster map with title

Inputs:

data title
1 2 3 My Cluster Map
4 5 6
7 8 9
10 11 12

Excel formula:

=CLUSTER_MAP({1,2,3;4,5,6;7,8,9;10,11,12}, "My Cluster Map")

Expected output:

"chart"

Example 3: Cluster map with plasma colormap

Inputs:

data color_map
1 5 3 plasma
4 2 6
7 9 8
2 4 1

Excel formula:

=CLUSTER_MAP({1,5,3;4,2,6;7,9,8;2,4,1}, "plasma")

Expected output:

"chart"

Example 4: Cluster map without colorbar

Inputs:

data colorbar
1 2 false
3 4
5 6

Excel formula:

=CLUSTER_MAP({1,2;3,4;5,6}, "false")

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
import io
import base64
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage

def cluster_map(data, title=None, color_map='viridis', colorbar='true'):
    """
    Create a hierarchically-clustered heatmap.

    See: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html

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

    Args:
        data (list[list]): Input matrix data.
        title (str, optional): Chart title. Default is None.
        color_map (str, optional): Color map. Valid options: Viridis, Plasma, Inferno, Magma, Cividis. Default is 'viridis'.
        colorbar (str, optional): Show colorbar. Valid options: True, False. Default is 'true'.

    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 all(isinstance(row, list) for row in data):
            return "Error: Invalid input - data must be a 2D list"

        # Convert to numpy array
        try:
            arr = np.array(data, dtype=float)
        except (ValueError, TypeError) as e:
            return f"Error: Could not convert data to numeric array: {str(e)}"

        if arr.ndim != 2:
            return "Error: Data must be a 2D array"

        if arr.size == 0:
            return "Error: Data array is empty"

        if arr.shape[0] < 2:
            return "Error: Need at least 2 rows for clustering"

        # Perform hierarchical clustering
        try:
            # Cluster rows
            row_linkage = linkage(arr, method='average')
            row_order = dendrogram(row_linkage, no_plot=True)['leaves']

            # Cluster columns
            col_linkage = linkage(arr.T, method='average')
            col_order = dendrogram(col_linkage, no_plot=True)['leaves']

            # Reorder data
            arr_clustered = arr[row_order, :][:, col_order]
        except Exception as e:
            return f"Error: Clustering failed: {str(e)}"

        # Create figure with subplots for dendrograms and heatmap
        fig = plt.figure(figsize=(10, 8))

        # Dendrogram for rows (left)
        ax_row = plt.subplot2grid((4, 4), (1, 0), rowspan=3)
        row_dend = dendrogram(row_linkage, orientation='left', no_labels=True)
        ax_row.set_xticks([])
        ax_row.set_yticks([])
        ax_row.axis('off')

        # Dendrogram for columns (top)
        ax_col = plt.subplot2grid((4, 4), (0, 1), colspan=3)
        col_dend = dendrogram(col_linkage, no_labels=True)
        ax_col.set_xticks([])
        ax_col.set_yticks([])
        ax_col.axis('off')

        # Heatmap (main)
        ax_heatmap = plt.subplot2grid((4, 4), (1, 1), rowspan=3, colspan=3)
        im = ax_heatmap.imshow(arr_clustered, cmap=color_map, aspect='auto')
        ax_heatmap.set_xticks([])
        ax_heatmap.set_yticks([])

        # Add colorbar if requested
        show_colorbar = colorbar.lower() == "true"
        if show_colorbar:
            plt.colorbar(im, ax=ax_heatmap)

        # Set title
        if title:
            fig.suptitle(title, y=0.98)

        plt.tight_layout()

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

Online Calculator