HEXBIN
Excel Usage
=HEXBIN(data, title, xlabel, ylabel, hexbin_cmap, gridsize, 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.hexbin_cmap(str, optional, default: “coolwarm”): Color map for bins.gridsize(int, optional, default: 100): Number of hexagons in X-direction.colorbar(str, optional, default: “true”): Show colorbar.
Returns (object): Matplotlib Figure object (standard Python) or base64 encoded PNG string (Pyodide).
Examples
Example 1: Basic hexbin plot
Inputs:
| data | |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 4 | 5 |
| 5 | 6 |
| 1.5 | 2.5 |
| 2.5 | 3.5 |
Excel formula:
=HEXBIN({1,2;2,3;3,4;4,5;5,6;1.5,2.5;2.5,3.5})
Expected output:
"chart"
Example 2: Hexbin with custom labels and Blues colormap
Inputs:
| data | title | xlabel | ylabel | hexbin_cmap | |
|---|---|---|---|---|---|
| 1 | 2 | Test Hexbin | X | Y | Blues |
| 2 | 3 | ||||
| 3 | 4 | ||||
| 4 | 5 | ||||
| 5 | 6 |
Excel formula:
=HEXBIN({1,2;2,3;3,4;4,5;5,6}, "Test Hexbin", "X", "Y", "Blues")
Expected output:
"chart"
Example 3: Hexbin with smaller grid size
Inputs:
| data | gridsize | |
|---|---|---|
| 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:
=HEXBIN({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: Hexbin without colorbar
Inputs:
| data | colorbar | |
|---|---|---|
| 1 | 2 | false |
| 2 | 3 | |
| 3 | 4 | |
| 4 | 5 | |
| 5 | 6 |
Excel formula:
=HEXBIN({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 hexbin(data, title=None, xlabel=None, ylabel=None, hexbin_cmap='coolwarm', gridsize=100, colorbar='true'):
"""
Create a hexagonal binning plot from data.
See: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hexbin.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.
hexbin_cmap (str, optional): Color map for bins. Valid options: Coolwarm, Viridis, Blues, Reds. Default is 'coolwarm'.
gridsize (int, optional): Number of hexagons in X-direction. Default is 100.
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 hexbin
hb = ax.hexbin(x_data, y_data, gridsize=gridsize, cmap=hexbin_cmap)
if str_to_bool(colorbar):
plt.colorbar(hb, 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)}"