You need to enable JavaScript to run this app. 如何使用d3.stratify将扁平数据集转换为层级数据以实现D3 treemap
优惠活动
大模型
产品
解决方案
定价
更多

如何使用d3.stratify将扁平数据集转换为层级数据以实现D3 treemap

实现分组嵌套效果的D3 Treemap开发步骤

1. 适配Treemap要求的层级数据结构

D3 Treemap的渲染依赖层级化的树结构,你提到的d3.stratify是常用的层级转换工具,实际开发中可以根据数据形态选两种实现路径,不需要硬套API:

路径A:基于d3.rollups直接聚合生成嵌套树(最直观,适合需要临时分组统计的场景)

用D3内置的聚合方法直接把扁平的原始数据集转成树结构,不需要手动维护父子ID:

// 第一步:按颜色分组,组内再按激活状态统计数量
const aggregatedGroups = d3.rollups(
  dataset,
  (items) => {
    const activeCount = items.filter(item => item.isActive).length;
    const inactiveCount = items.filter(item => !item.isActive).length;
    return [
      { name: 'active', value: activeCount },
      { name: 'inactive', value: inactiveCount }
    ]
  },
  item => item.color
).map(([colorName, children]) => ({
  name: colorName,
  children: children
}));

// 补一层全局根节点(Treemap要求最外层有统一的根容器)
const nestedRootData = {
  name: 'chart-root',
  children: aggregatedGroups
}

路径B:基于d3.stratify转换长表结构(适合已经带父子标识的数据集)

如果你坚持用stratify做转换,需要先把聚合好的统计结果,展开成stratify可识别的、每行带唯一ID和父ID的平铺表格式:

// 把嵌套结构展开成适配stratify的平铺长表
const flatStratifyRows = [];
// 追加根节点行
flatStratifyRows.push({ id: 'chart-root', parentId: '' });
// 追加一级颜色组节点行
aggregatedGroups.forEach(group => {
  flatStratifyRows.push({
    id: group.name,
    parentId: 'chart-root'
  });
  // 追加二级状态子节点行,附带计数值
  group.children.forEach(child => {
    flatStratifyRows.push({
      id: `${group.name}-${child.name}`,
      parentId: group.name,
      value: child.value
    })
  });
});

// 初始化stratify转换器,指定ID和父ID的取值字段
const convertToHierarchy = d3.stratify()
  .id(row => row.id)
  .parentId(row => row.parentId);
const hierarchyRoot = convertToHierarchy(flatStratifyRows);

2. 配置Treemap布局计算逻辑

拿到层级结构后,用Treemap生成器计算每个节点的坐标、尺寸:

// 定义画布尺寸
const canvasWidth = 800;
const canvasHeight = 600;

// 初始化Treemap布局生成器
const treemapGenerator = d3.treemap()
  .size([canvasWidth, canvasHeight])
  .padding(2) // 块间留2px间隙,强化分组区分
  .round(true); // 坐标取整,避免渲染边缘模糊

// 给层级节点绑定数值(决定每个块的面积大小),执行布局计算
hierarchyRoot
  .sum(nodeData => nodeData.value)
  .sort((a, b) => b.value - a.value);

const calculatedLayout = treemapGenerator(hierarchyRoot);

3. 渲染匹配预期效果的矩形块

按照你要的视觉效果做分层渲染,避免非叶子节点的填充遮挡下层色块:

  • 叶子节点(最细的状态块):激活状态用黄色填充,非激活状态用白色填充
  • 一级颜色组节点:仅绘制对应颜色的边框,不做填充,强化大分组的视觉区分
// 初始化SVG画布
const svgContainer = d3.select('#chart-container')
  .append('svg')
  .attr('width', canvasWidth)
  .attr('height', canvasHeight);

// 渲染最细的叶子状态块
svgContainer.selectAll('rect.leaf-block')
  .data(calculatedLayout.leaves())
  .join('rect')
  .attr('class', 'leaf-block')
  .attr('x', d => d.x0)
  .attr('y', d => d.y0)
  .attr('width', d => d.x1 - d.x0)
  .attr('height', d => d.y1 - d.y0)
  .attr('fill', d => d.data.id.includes('active') ? '#f9e049' : '#ffffff')
  .attr('stroke', '#e0e0e0');

// 渲染三个大颜色组的外边框
svgContainer.selectAll('rect.group-border')
  .data(calculatedLayout.children)
  .join('rect')
  .attr('class', 'group-border')
  .attr('x', d => d.x0)
  .attr('y', d => d.y0)
  .attr('width', d => d.x1 - d.x0)
  .attr('height', d => d.y1 - d.y0)
  .attr('fill', 'none')
  .attr('stroke', d => d.data.name) // 边框色匹配对应组的红/蓝/绿
  .attr('stroke-width', 3);

开发注意点

  • 渲染顺序要保持先画下层叶子块,再画上层组边框,不然边框会被色块遮挡
  • 间隙、颜色、边框宽度都可以根据实际视觉需求调整参数
  • 不需要给非叶子节点设置填充色,否则会完全盖住下层的叶子内容块

内容的提问来源于stack exchange,提问作者marielle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 18:36:04