HEATMAP
Excel Usage
=HEATMAP(data, title, xlabel, ylabel, color_map, values, colorbar)
data(list[list], required): Input matrix data.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.color_map(str, optional, default: “viridis”): Color map.values(str, optional, default: “false”): Show values.colorbar(str, optional, default: “true”): Show colorbar.
Returns (object): Matplotlib Figure object (standard Python) or base64 encoded PNG string (Pyodide).
Examples
Example 1: Basic 3x3 heatmap
Inputs:
| data | ||
|---|---|---|
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
Excel formula:
=HEATMAP({1,2,3;4,5,6;7,8,9})
Expected output:
"chart"
Example 2: Heatmap with title and labels
Inputs:
| data | title | xlabel | ylabel | |
|---|---|---|---|---|
| 1 | 2 | My Heatmap | X | Y |
| 3 | 4 |
Excel formula:
=HEATMAP({1,2;3,4}, "My Heatmap", "X", "Y")
Expected output:
"chart"
Example 3: Heatmap with plasma colormap
Inputs:
| data | color_map | ||
|---|---|---|---|
| 1 | 2 | 3 | plasma |
| 4 | 5 | 6 |
Excel formula:
=HEATMAP({1,2,3;4,5,6}, "plasma")
Expected output:
"chart"
Example 4: Heatmap showing values
Inputs:
| data | values | |
|---|---|---|
| 1.5 | 2.5 | true |
| 3.5 | 4.5 |
Excel formula:
=HEATMAP({1.5,2.5;3.5,4.5}, "true")
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 heatmap(data, title=None, xlabel=None, ylabel=None, color_map='viridis', values='false', colorbar='true'):
"""
Create a heatmap from a matrix of data.
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.
xlabel (str, optional): Label for X-axis. Default is None.
ylabel (str, optional): Label for Y-axis. Default is None.
color_map (str, optional): Color map. Valid options: Viridis, Plasma, Inferno, Magma, Cividis. Default is 'viridis'.
values (str, optional): Show values. Valid options: True, False. Default is 'false'.
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"
# Create figure
fig, ax = plt.subplots(figsize=(8, 6))
# Create heatmap
im = ax.imshow(arr, cmap=color_map, aspect='auto')
# Add colorbar if requested
show_colorbar = colorbar.lower() == "true"
if show_colorbar:
plt.colorbar(im, ax=ax)
# Add values if requested
show_values = values.lower() == "true"
if show_values:
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
text = ax.text(j, i, f'{arr[i, j]:.2f}',
ha="center", va="center", color="white")
# Set labels
if title:
ax.set_title(title)
if xlabel:
ax.set_xlabel(xlabel)
if ylabel:
ax.set_ylabel(ylabel)
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)}"