2017-12-27 807 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/ –