D3.js将嵌套数据添加到父组

时间:2015-07-16 10:02:43

标签: d3.js

我有一个'父'矩形,它是围绕较小的矩形绘制的。 Here's a live example

数据如下所示:

var allData = [{x:50, y: 60, height: 40, width: 30, 
                  defects: [
                { x: 53, y: 61, width: 10, height: 10 },
                { x: 55, y: 71, width: 10, height: 10 },
                { x: 60, y: 76, width: 10, height: 10 }]},
              {x:150, y: 160, height: 50, width: 40, 
                  defects: [
                { x: 151, y: 165, width: 5, height: 5 },
                { x: 160, y: 169, width: 5, height: 5 },
                { x: 165, y: 170, width: 5, height: 5 }]
              }];

如您所见,有2个矩形,每个矩形有3个较小的矩形,称为缺陷。

我正在尝试将其可视化,但希望在1个选择中进行,以便稍后我可以更轻松地将其转换。

这是我到目前为止所得到的:

var svg = d3.select('#test svg')
    .attr("width", 800)
    .attr("height", 500);

var groups = svg.selectAll('.defect-group')
      .data(allData)
      .enter()
      .append('g').attr('class', 'defect-group')
      .append('rect')
      .attr('class', 'defect-area')
      .attr('width', function(d) {return d.width})
      .attr('height', function(d) {return d.height})
      .attr('x', function(d) {return d.x})
      .attr('y', function(d) {return d.y});

var defects = groups.selectAll('.defects')
  .data(function(d) {
    return d.defects;
  })
  .enter()
  .append('rect')
  .attr('class', 'defect')
  .attr('width', function(d) {return d.width})
  .attr('height', function(d) {return d.height})
  .attr('x', function(d) {return d.x})
  .attr('y', function(d) {return d.y});

结果是:

enter image description here

如您所见,我(意外地)嵌套了'rect'元素中的缺陷。由于rect不能有子元素我想将缺陷也放在'缺陷组'组中,我已经尝试但似乎无法弄清楚如何将它们放在父组中。

怎么做?

1 个答案:

答案 0 :(得分:0)

只需将g元素取出并附加所有内容即可。

在您的代码中,更改

var groups = svg.selectAll('.defect-group')
      .data(allData)
      .enter()
      .append('g').attr('class', 'defect-group')
      .append('rect')
      .attr('class', 'defect-area')
      .attr('width', function(d) {return d.width})
      .attr('height', function(d) {return d.height})
      .attr('x', function(d) {return d.x})
      .attr('y', function(d) {return d.y});

var groups = svg.selectAll('.defect-group')
        .data(allData)
        .enter()
        .append('g').attr('class', 'defect-group')

groups
        .append('rect')
        .attr('class', 'defect-area')
        .attr('width', function (d) { return d.width })
        .attr('height', function (d) { return d.height })
        .attr('x', function (d) { return d.x })
        .attr('y', function (d) { return d.y });
相关问题