如何使用D3.js将给定JSON二维数组数据渲染为矩阵热图
基于给定矩阵数据的D3热图实现
针对你提供的{"data":[[8,2],[5,4],[9,6]]}结构,实现矩阵热图的核心逻辑是将二维数组的每个元素与对应行列位置的彩色矩形做一一映射,不需要对原始数据做复杂的格式转换。
核心实现步骤
- 匹配矩阵维度:先计算原始数据的总行列数——本次示例数据为3行2列,每个单元格的位置完全对应原数组的行、列索引,不会出现排布错位
- 展平嵌套数据:遍历二维数组生成逐单元格的记录集,每条记录存储当前数值、所在行索引、所在列索引,满足D3的数据绑定要求
- 配置匹配用的三类比例尺:
- 横向位置比例尺:将列索引范围映射为SVG绘图区的横向像素区间,定位每个矩形的左边缘坐标
- 纵向位置比例尺:将行索引范围映射为SVG绘图区的纵向像素区间,定位每个矩形的上边缘坐标,适配D3左上角为原点的默认坐标系
- 颜色映射比例尺:自动遍历所有单元格数值计算上下限,将数值范围映射为连续色阶,数值越高对应颜色权重越深
- 渲染单元格图形:为每条展平后的数据生成对应尺寸的矩形,通过比例尺绑定坐标、填充色,可选添加白色分割线区分相邻单元格
- (可选)添加文本标注:在每个矩形的中心位置标注原始数值,降低热图的读图成本
可直接复用的核心代码
// 本地引入D3 v7版本后运行以下逻辑 const rawInput = {"data":[[8,2],[5,4],[9,6]]}; const matrix = rawInput.data; // 基础参数配置 const cellSize = 30; const margin = {top: 40, right: 40, bottom: 40, left: 40}; const totalRows = matrix.length; const totalCols = matrix[0].length; // 计算SVG画布整体尺寸 const canvasWidth = margin.left + margin.right + totalCols * cellSize; const canvasHeight = margin.top + margin.bottom + totalRows * cellSize; // 展平二维矩阵为可绑定的单元格数据 const cellList = []; matrix.forEach((row, rowIdx) => { row.forEach((val, colIdx) => { cellList.push({ value: val, rowIdx, colIdx }); }); }); // 初始化SVG画布 const svg = d3.select("body") .append("svg") .attr("width", canvasWidth) .attr("height", canvasHeight) .append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // 配置位置比例尺 const xPosScale = d3.scaleLinear() .domain([0, totalCols]) .range([0, totalCols * cellSize]); const yPosScale = d3.scaleLinear() .domain([0, totalRows]) .range([0, totalRows * cellSize]); // 配置颜色比例尺 const valRangeMin = d3.min(cellList, d => d.value); const valRangeMax = d3.max(cellList, d => d.value); const colorScale = d3.scaleSequential() .domain([valRangeMin, valRangeMax]) .interpolator(d3.interpolateBlues); // 绘制热图单元格 svg.selectAll("rect") .data(cellList) .join("rect") .attr("x", d => xPosScale(d.colIdx)) .attr("y", d => yPosScale(d.rowIdx)) .attr("width", cellSize) .attr("height", cellSize) .attr("fill", d => colorScale(d.value)) .attr("stroke", "#ffffff"); // 添加单元格数值标注 svg.selectAll("text") .data(cellList) .join("text") .attr("x", d => xPosScale(d.colIdx) + cellSize / 2) .attr("y", d => yPosScale(d.rowIdx) + cellSize / 2) .attr("text-anchor", "middle") .attr("dominant-baseline", "middle") .text(d => d.value) .attr("fill", "#ffffff") .attr("font-size", "12px");
运行效果说明:最终渲染的热图会完全匹配原矩阵的排布逻辑,第一行显示
8、2两个单元格,第二行显示5、4,第三行显示9、6,颜色会随数值从2到9逐步加深,不需要额外调整坐标轴方向。
内容的提问来源于stack exchange,提问作者J. Sanz
相关产品推荐
相关产品推荐

