2017-12-27 210 views
0

试图了解如何应对D3嵌套数据,我想出了这个例子:D3.js - 嵌套数据的作品,但选择不遵循

<script> 

data = [ 
{ Name: "jim", color: "blue", Points: [{x:0, y:5 }, {x:25, y:7 }, {x:50, y:13}] }, 
{ Name: "bob", color: "green", Points: [{x:0, y:10}, {x:27, y:30}, {x:57, y:60}] } 
]; 

var print = function(d){d3.select("body li") 
    .selectAll("b") 
    .data(d) 
    .enter() 
     .append("b") 
     .text(function(i){return ' - ' + i.x;});} 

d3.select("body") 
    .selectAll("li") 
    .data(data) 
    .enter() 
     .append("li") 
     .text(function(d){print(d.Points);}); 

</script> 

我本来期望这产生这样:

<li> 
    <b> - 0</b> 
    <b> - 25</b> 
    <b> - 50</b> 
</li> 
<li> 
    <b> - 0</b> 
    <b> - 27</b> 
    <b> - 57</b> 
</li> 

而是产生如下:

<li> 
    <b> - 0</b> 
    <b> - 27</b> 
    <b> - 57</b> 
</li> 
<li></li> 

我明白,当我选择“身体里”我本身将现有的两个“li”放在一起,我只给出一个只在第一个“li”中出现的“d”数据,但我真的不明白D3如何在这种情况下工作以及如何遍历“li”。

+1

你原来的方法效果this'给你的函数:HTTPS:/ /jsfiddle.net/nqzak4y4/ –

回答

2

我创建li第一,然后使用绑定的数据来创建子弹:如果你使用`each`并通过`

data = [ 
{ Name: "jim", color: "blue", Points: [{x:0, y:5 }, {x:25, y:7 }, {x:50, y:13}] }, 
{ Name: "bob", color: "green", Points: [{x:0, y:10}, {x:27, y:30}, {x:57, y:60}] } 
]; 
//original selection creates two 'li' objects 
var lines = d3.select("body") 
    .selectAll("li") 
    .data(data) 
    .enter() 
     .append("li"); 

//using the same selection; we can iterate (function(d,i) where i is the index) over each 'li' object 
//to do so, we create a new selection where the data is pulled from the data in the 'lines' variable 
var bullets = lines.selectAll('b') 
    .data(function(d) { return d.Points; }) //returns the Points variable from the data already bound to the variable 'lines' 
    .enter() 
    .append('b') 
    .text(function(d,i) {return ' - ' + d.x; }); //iterates (i) over each lines object and return the x variable from the bound data. 
+0

我可以在哪里了解这个?我不太明白发生了什么 – user3755529

+0

您只需使用相同的数据嵌套逻辑创建选择/数据/输入模式。还有一个d3.nest函数可用于汇总:http://bl.ocks.org/phoebebright/raw/3176159/ –