TRIANGULAR_HEATMAP
Excel Usage
=TRIANGULAR_HEATMAP(data, title, color_map, triangle, values, colorbar)
data(list[list], required): Input matrix data.title(str, optional, default: null): Chart title.color_map(str, optional, default: “viridis”): Color map.triangle(str, optional, default: “lower”): Triangle part (‘lower’, ‘upper’).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: Lower triangular heatmap
Inputs:
| data | triangle | ||
|---|---|---|---|
| 1 | 2 | 3 | lower |
| 4 | 5 | 6 | |
| 7 | 8 | 9 |
Excel formula:
=TRIANGULAR_HEATMAP({1,2,3;4,5,6;7,8,9}, "lower")
Expected output:
"chart"
Example 2: Upper triangular heatmap
Inputs:
| data | triangle | ||
|---|---|---|---|
| 1 | 2 | 3 | upper |
| 4 | 5 | 6 | |
| 7 | 8 | 9 |
Excel formula:
=TRIANGULAR_HEATMAP({1,2,3;4,5,6;7,8,9}, "upper")
Expected output:
"chart"
Example 3: Triangular heatmap with title
Inputs:
| data | title | triangle | |
|---|---|---|---|
| 1 | 2 | My Triangle | lower |
| 3 | 4 |
Excel formula:
=TRIANGULAR_HEATMAP({1,2;3,4}, "My Triangle", "lower")
Expected output:
"chart"
Example 4: Triangular heatmap showing values
Inputs:
| data | triangle | values | ||
|---|---|---|---|---|
| 1.5 | 2.5 | 3.5 | lower | true |
| 4.5 | 5.5 | 6.5 | ||
| 7.5 | 8.5 | 9.5 |
Excel formula:
=TRIANGULAR_HEATMAP({1.5,2.5,3.5;4.5,5.5,6.5;7.5,8.5,9.5}, "lower", "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 triangular_heatmap(data, title=None, color_map='viridis', triangle='lower', values='false', colorbar='true'):
"""
Create a lower or upper triangular 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'.
triangle (str, optional): Triangle part ('lower', 'upper'). Valid options: Lower, Upper. Default is 'lower'.
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 mask for triangular display
mask = np.zeros_like(arr, dtype=bool)
if triangle.lower() == "lower":
# Mask upper triangle
mask = np.triu(np.ones_like(arr, dtype=bool), k=1)
elif triangle.lower() == "upper":
# Mask lower triangle
mask = np.tril(np.ones_like(arr, dtype=bool), k=-1)
else:
return f"Error: Invalid triangle parameter '{triangle}'. Must be 'lower' or 'upper'"
# Apply mask by setting to NaN
arr_masked = arr.copy()
arr_masked[mask] = np.nan
# Create figure
fig, ax = plt.subplots(figsize=(8, 6))
# Create heatmap
im = ax.imshow(arr_masked, 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]):
if not mask[i, j]:
text = ax.text(j, i, f'{arr[i, j]:.2f}',
ha="center", va="center", color="white")
# Set labels
if title:
ax.set_title(title)
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)}"