D3 如何修复树图中没有根?

D3 how to fix no root in treemap?

我为 freecodecamp 做树图项目 得到一个错误(控制台)没有根。你能帮我吗?我做错了什么?

https://codepen.io/DeanWinchester88/pen/xxrjLrM

  const root  = d3.stratify()
                  .id(  (d) =>  d.name)
                  .parentId(  (d) => d.parent)
                  (gameData)

d3-hierarchy documentation

Before you can compute a hierarchical layout, you need a root node. If your data is already in a hierarchical format, such as JSON, you can pass it directly to d3.hierarchy; otherwise, you can rearrange tabular data, such as comma-separated values (CSV), into a hierarchy using d3.stratify.

您的数据已经是分层格式,因此您不需要使用 d3.stratify

此外,documentation

You must call node.sum or node.count before invoking a hierarchical layout that requires node.value, such as d3.treemap.

在此之后,您处理数据的代码可能如下所示:

// the plus sign turns the string into a number
const hierarchy = d3.hierarchy(gameData).sum(d => +d.value);
  
const treemap = d3.treemap()
  .size([width, height])
  .padding(4);
  
const root = treemap(hierarchy);

最后,对于设置宽度属性,你有 .attr("width", (d) => d.x1 - d.x2) 但它应该是 .attr("width", (d) => d.x1 - d.x0)