D3.js 具有d3的嵌套(分层)数据

D3.js 具有d3的嵌套(分层)数据,d3.js,nested,hierarchical-data,D3.js,Nested,Hierarchical Data,我读过博斯托克的“”教程,但我不能完全理解使用嵌套数据 我已将问题简化为如下数据集: var数据=[{ “id”:“foo”, “行”:0, “col”:0, “行大小”:200, “col_尺寸”:100, “模块”:[{ “id”:“foo1”, “行”:0, “col”:0 }, { “id”:“foo2”, “行”:1, “col”:0 }] }, { “id”:“bar”, “行”:0, “col”:1, “行大小”:200, “col_尺寸”:100, “模块”:[{ “id”:“

我读过博斯托克的“”教程,但我不能完全理解使用嵌套数据

我已将问题简化为如下数据集:

var数据=[{
“id”:“foo”,
“行”:0,
“col”:0,
“行大小”:200,
“col_尺寸”:100,
“模块”:[{
“id”:“foo1”,
“行”:0,
“col”:0
}, {
“id”:“foo2”,
“行”:1,
“col”:0
}]
}, {
“id”:“bar”,
“行”:0,
“col”:1,
“行大小”:200,
“col_尺寸”:100,
“模块”:[{
“id”:“bar1”,
“行”:0,
“col”:1
}, {
“id”:“bar2”,
“行”:1,
“col”:1
}]

}]
这应该可以。我还没有测试过它,所以可能会有错误,但整体结构就是你想要的

var svg = d3.select("body").append("svg") // here you'll also want to apply width and height .attr's
var mainG = svg.append("g") // this you'll also want to translate(20,20) as your mockup suggests

// Now bind the outer level, to produce a 2-element selection bound to 'data'
var gOuter = mainG.selectAll("g.outside_box").data(data)
var gOuterEnter = gOuter.enter().append("g")
    .attr("class", "outside_box")
    // also to this you can apply translation as you wish

gOuterEnter.append("rect") // and set the rect's attributes as needed
gOuterEnter.append("text") // and set the text's attributes and text as needed
gOuterEnter.append("g")
  .attr("class", "inside_box")

// Now comes the work with the nested data:
var gModules = gOuterEnter.select(".inside_box").selectAll("g").data(function(d) {
  // here d is the outer datum, and lets you access
  // its nested 'modules' array, which is what you want
  // to return, as instructed by Bostocks "Nested Selections" tutorial
  return d.modules
})

var gModulesEnter = gModules.enter()
  .append("g")

gModulesEnter.append("rect") // and set attributes
gModulesEnter.append("text")
  .text(function(m) {
    // here m is each module's datum, so you can return its id
    // to set the text to what you want
    return d.id
  })
感谢
.data(函数(d){returnd.modules;})
对我来说是个诀窍。