d3.js 在D3 v7中为树形图格式化平面JSON

r6vfmomb  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(194)

我有一个平面JSON数组,并尝试使用下面的代码将其格式化为D3.js v7中的树表示。我对数据进行分组,然后使用层次结构来创建链接和节点,如文档中所述,但当我创建图表时,它会生成一个空的根和最后一个子节点。
请参阅:https://codepen.io/nvelden/pen/LYmveWz?editors=1111

//Load data
const data = [
{"root":"project","project_nr":"project 1","department":"1","devision":"A"},
{"root":"project","project_nr":"project 1","department":"1","devision":"B"},
{"root":"project","project_nr":"project 1","department":"2","devision":"A"},
{"root":"project","project_nr":"project 2","department":"3","devision":"A"}
]

var margin = {top: 10, right: 10, bottom: 10, left: 50},
width = 500 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var tree = d3.cluster()
    .size([height, width])
    .size([height-margin.top-margin.bottom,width-margin.left-margin.right]); 

var groupedData = d3.group(data,
                          d => d.root,
                          d => d.project_nr,
                          d => d.department,
                          d => d.devision)

//Create root 
var root = d3.hierarchy(groupedData)

//Attach canvas element
var svg = d3.select("body")
            .append("svg")
            .attr("width", 1000)
            .attr("height", 1000);  

var g = svg
        .append("g")
        .attr('transform','translate('+ margin.left +','+ margin.right +')');

var link = g.selectAll(".link")
        .data(tree(root).links())
        .enter()
        .append("path")
        .attr("class", "link")
        .attr("d", d3.linkHorizontal()
                .x(function(d) {return d.y;})
                .y(function(d) {return d.x;}));      

var node = g.selectAll(".node")
        .data(root.descendants())
        .enter()
        .append("g") 
        .attr("class", "link") 
        .attr("class", d => 
        { return "node" + (d.children ? " node--internal" : " node--leaf")})
        .attr("transform", d => 
        { return "translate(" + d.y + ","+ d.x + ")" ; })

var text = g.selectAll("text")
        .data(root.descendants())
        .enter().append("text")
        .text(d => d.data[0])
        .attr('dy', "0.32em")
        .attr("class", "label glow") 
        .attr('text-anchor', "center")
        .attr("x", d => d.y)
        .attr("y", d => d.x);

node.append("circle")
    .attr("r", 2.5)

我应该如何格式化数据以获得下图中的树?

jgovgodb

jgovgodb1#

如果我们假设顶层只有一个项目,那么最好不要按项目分组;同样,由于部门是叶节点,所以最好不要按部门分组。

groupedData = d3.group(
    data,
    (d) => d.project_nr,
    (d) => d.department
  );

但是现在我们缺少了根节点中的“project”名称,以及叶节点中的部门名称。

({ data }) => Array.isArray(data) ? data[0] || "project" : data.devision

下面是一个笔记本,上面有完整的代码:https://observablehq.com/@recifs/data-to-tree--support

相关问题