当前位置: 动力学知识库 > 问答 > 编程问答 >

d3.js - Nested (hierarchical) data with d3

问题描述:

I've read Bostock's "Nested Selections" tutorial but I couldn't quite wrap my head around using nested data.

I've simplified my problem to a data set like this:

var data = [{

"id": "foo",

"row": 0,

"col": 0,

"row_size": 200,

"col_size": 100,

"modules": [{

"id": "foo1",

"row": 0,

"col": 0

}, {

"id": "foo2",

"row": 1,

"col": 0

}]

}, {

"id": "bar",

"row": 0,

"col": 1,

"row_size": 200,

"col_size": 100,

"modules": [{

"id": "bar1",

"row": 0,

"col": 1

}, {

"id": "bar2",

"row": 1,

"col": 1

}]

}]

网友答案:

This should do it. I haven't tested it, so it's possible there are errors, but the overall structure is what you're after.

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
  })
分享给朋友:
您可能感兴趣的文章:
随机阅读: