gpt4 book ai didi

d3.js - 如何在 D3 中为树布局指定自定义子项和父项属性

转载 作者:行者123 更新时间:2023-12-02 17:30:05 25 4
gpt4 key购买 nike

如果我将以下 JSON 提供给 d3,它就可以工作。

  {
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}

但是如果我改成following就不行了。请注意,children 中的变化是 CAPITAL Cparent 中的 P 而不是 name 我有 DeptCode所以问题是有没有办法指示 d3 使用 Children 而不是 children,Parent 而不是 < strong>parent 和 DeptCode 而不是 name

  {
"DeptCode": "Top Level",
"Parent": "null",
"Children": [
{
"DeptCode": "Level 2: A",
"Parent": "Top Level",
"Children": [
{
"DeptCode": "Son of A",
"Parent": "Level 2: A"
},
{
"DeptCode": "Daughter of A",
"Parent": "Level 2: A"
}
]
},
{
"DeptCode": "Level 2: B",
"Parent": "Top Level"
}
]
}

编辑:我刚找到 this .但我不知道该怎么做。有人可以详细说明吗?

最佳答案

对于给定的数据集

var treeData = [
{
"DeptCode": "Top Level",
"Parent": "null",
"Children": [
{
"DeptCode": "Level 2: A",
"Parent": "Top Level",
"Children": [
{
"DeptCode": "Son of A",
"Parent": "Level 2: A"
},
{
"DeptCode": "Daughter of A",
"Parent": "Level 2: A"
}
]
},
{
"DeptCode": "Level 2: B",
"Parent": "Top Level"
}
]
}
];

这就是你如何连接它:

因为数据有而不是默认的

var tree = d3.layout.tree()
.size([height, width])
.children(function(d){return d.Children;});//this will provide children.

对于节点上的文本:

  nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -13 : 13; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.DeptCode; })//the new label name
.style("fill-opacity", 1e-6);

对于可折叠节点做:

// Toggle children on click.
function click(d) {
if (d.Children) {
d._children = d.Children;//since the children is stored in Children.
d.Children = null;
} else {
d.Children = d._children;
d._children = null;
}
update(d);
}

工作代码 here

希望这对您有所帮助!

关于d3.js - 如何在 D3 中为树布局指定自定义子项和父项属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34527623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com