2013-11-14 54 views
0

我正在嘗試通過一些D3教程,所以請忍受我的noob問題。據我瞭解,爲了創建某種類型的新元素,您必須在不存在的元素上使用.selectAll(),然後使用.append()來創建它們。如果沒有現有的元素與指定的選擇器匹配,那麼這很有效,但如果存在,它將選擇那些元素並在其中添加新元素。就拿這個例子:使用selectAll()創建新元素,同時保留現有元素

d3.json("virusOrigins.json", function(dataset) { 
    var w = 200; 
    var h = 300; 
    var barPadding = 1; 
    var xScale = d3.scale.linear() 
        .domain([0, d3.max(dataset, function(d) { return d.value; })]) 
        .rangeRound([5, w]) 
        .nice(); 

    var svg = d3.select("body") 
     .append("svg") 
     .attr("width", w) 
     .attr("height", h) 

     // append base rectangle 
     .append("rect") 
     .attr("width", w) 
     .attr("height", h) 
     .attr("fill", "#ccc"); 
    svg.selectAll("rect.bars") 
     .data(dataset) 
     .enter() 
     .append("rect") 
     .attr("y", function(d, i) { 
      return i * (h/dataset.length); 
     }) 
     .attr("x", 0) 
     .attr("width", function (d) { 
      return xScale(d.value); 
     }) 
     .attr("height", function(d) { 
      return (h/dataset.length) - barPadding; 
     }) 
     .attr("fill", "#f33") 
     .classed("bars", true); 
}); 

這將導致以下HTML:

<svg width="200" height="300"> 
    <rect width="200" height="300" fill="#ccc"> 
     <rect y="0" x="0" width="13" height="32.333333333333336" fill="#f33" class="bars"></rect> 
     <rect y="33.333333333333336" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect> 
     <rect y="66.66666666666667" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect> 
     <rect y="100" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect> 
     <rect y="133.33333333333334" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect> 
     <rect y="166.66666666666669" x="0" width="200" height="32.333333333333336" fill="#f33" class="bars"></rect> 
     <rect y="200" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect> 
     <rect y="233.33333333333334" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect> 
     <rect y="266.6666666666667" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect> 
    </rect> 
</svg> 

我怎樣才能動態創建矩形的底座矩形的是兄弟姐妹?

回答

1

您將rect保存在svg中,然後附加到它。只需保存svg元素來代替:

var svg = d3.select("body") 
    .append("svg") 
    .attr("width", w) 
    .attr("height", h); 

// append base rectangle 
svg.append("rect") 
    .attr("width", w) 
    .attr("height", h) 
    .attr("fill", "#ccc"); 
svg.selectAll("rect.bars") 
    .data(dataset) 
    .enter() 
    .append("rect") 
// etc 
+0

哦,我明白了。通過使用鏈接,初始矩形成爲該選擇的一部分。我認爲它會引用svg元素本身。 –

1

如下更改數據的插入:

svg.selectAll("rect.bars") 
    .data(dataset, function(d){return d;}) <-- Here * 
    .enter() 
    .append("rect") 
    ... 
  • 添加函數來告訴你要考慮到所有的數據未對現有元素,但真正產生新的元素。

欲瞭解更多信息,請參閱本文章的example 3瞭解D3.js中的selectAll,data,enter,append sequence。

+0

拉爾斯答案是一個我一直在尋找,但是這是一個非常豐富的職位。在我的D3研究中,我還沒有得到那麼多,但我肯定遲早會對我的頭腦發火。謝謝。 –