HIST2D

Excel Usage

=HIST2D(data, title, xlabel, ylabel, histtwod_cmap, bins, colorbar)
  • data (list[list], required): Input data (X, Y).
  • title (str, optional, default: null): Chart title.
  • xlabel (str, optional, default: null): Label for X-axis.
  • ylabel (str, optional, default: null): Label for Y-axis.
  • histtwod_cmap (str, optional, default: “coolwarm”): Color map for bins.
  • bins (int, optional, default: 10): Number of bins.
  • colorbar (str, optional, default: “true”): Show colorbar.

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

Examples

Example 1: Basic 2D histogram

Inputs:

data
1 2
2 3
3 4
4 5
5 6
1.5 2.5
2.5 3.5

Excel formula:

=HIST2D({1,2;2,3;3,4;4,5;5,6;1.5,2.5;2.5,3.5})

Expected output:

"chart"

Example 2: 2D histogram with custom labels and Reds colormap

Inputs:

data title xlabel ylabel histtwod_cmap
1 2 Test Hist2D X Y Reds
2 3
3 4
4 5
5 6

Excel formula:

=HIST2D({1,2;2,3;3,4;4,5;5,6}, "Test Hist2D", "X", "Y", "Reds")

Expected output:

"chart"

Example 3: 2D histogram with fewer bins

Inputs:

data bins
1 2 5
2 3
3 4
4 5
5 6
1.5 2.5
2.5 3.5
3.5 4.5

Excel formula:

=HIST2D({1,2;2,3;3,4;4,5;5,6;1.5,2.5;2.5,3.5;3.5,4.5}, 5)

Expected output:

"chart"

Example 4: 2D histogram without colorbar

Inputs:

data colorbar
1 2 false
2 3
3 4
4 5
5 6

Excel formula:

=HIST2D({1,2;2,3;3,4;4,5;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

def hist2d(data, title=None, xlabel=None, ylabel=None, histtwod_cmap='coolwarm', bins=10, colorbar='true'):
    """
    Create a 2D histogram plot from data.

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

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

    Args:
        data (list[list]): Input data (X, Y).
        title (str, optional): Chart title. Default is None.
        xlabel (str, optional): Label for X-axis. Default is None.
        ylabel (str, optional): Label for Y-axis. Default is None.
        histtwod_cmap (str, optional): Color map for bins. Valid options: Coolwarm, Viridis, Blues, Reds. Default is 'coolwarm'.
        bins (int, optional): Number of bins. Default is 10.
        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

    def str_to_bool(s):
        return s.lower() == "true" if isinstance(s, str) else bool(s)

    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"

        # Extract X and Y columns
        x_data = []
        y_data = []

        for row in data:
            if len(row) >= 2:
                try:
                    x_data.append(float(row[0]))
                    y_data.append(float(row[1]))
                except (TypeError, ValueError):
                    continue

        if not x_data or not y_data:
            return "Error: Data must have at least 2 columns with numeric values"

        # Create plot
        fig, ax = plt.subplots(figsize=(8, 6))

        # Plot 2D histogram
        h = ax.hist2d(x_data, y_data, bins=bins, cmap=histtwod_cmap)

        if str_to_bool(colorbar):
            plt.colorbar(h[3], ax=ax, label='Count')

        if title:
            ax.set_title(title)
        if xlabel:
            ax.set_xlabel(xlabel)
        if ylabel:
            ax.set_ylabel(ylabel)

        plt.tight_layout()

        # Return based on platform
        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