简体   繁体   English

d3.js遍历分层数据

[英]d3.js traverse hierarchical data

In d3.js, how do you use .data on this kind of hierarchy? 在d3.js中,如何在这种层次结构上使用.data?

data = [{node : 1, subProperties : ["A", "B", "C"]}
       ,{node : 2, subProperties : ["D", "E", "F"]}
]

d3.select("body")
  .data(data)
  .append("g") //for the node (1 and 2)
  .???         //append a "sub"-g for the subProperties (A,B,C and D,E,F)

Basically, I would like to create a set of nodes, and for each sub property, append something else grouped under the same node. 基本上,我想创建一组节点,并为每个子属性添加在同一节点下分组的其他内容。

Or is .data only used for "serial" structures? 还是.data仅用于“串行”结构? If so, how should hierarchichal data like this be treated? 如果是这样,应该如何处理这样的层次数据?

I'm not looking the the layout-features of d3, just how to "iterate" over tree-like hierarchies. 我不是在看d3的布局功能,而只是在树状层次结构上“迭代”。 Thank you! 谢谢!

First you probably want to create a group inside a svg element. 首先,您可能想在svg元素内创建一个组。 If you do that, you can create the main group first, and for each element, create the subgroups, binding the subProperties attribute to this subgroups: 如果这样做,则可以首先创建主组,然后为每个元素创建子组,并将subProperties属性绑定到该子组:

var svg = d3.select('#chart').append('svg')
  .attr('width', 100)
 .attr('height', 100);

var data = [
  {node : 1, subProperties : ["A", "B", "C"]},
  {node : 2, subProperties : ["D", "E", "F"]}
];

var mainGroups = svg.selectAll('g.main')
 .data(data)
 .enter()
 .append('g')
 .classed('main', true);

mainGroups.selectAll('g.sub')
 .data(function(d) { return d.subProperties; })
 .enter()
 .append('g')
 .classed('sub', true);

I wrote a jsfiddle with the code here. 我在这里用代码编写了一个jsfiddle Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM