2014-03-19 161 views
7

今天我用enter-update-exit邏輯創建了一個簡單的條形圖 - 一切正常。現在我將使用折線圖來做同樣的事情 - 圖表的整個數據集可以隨時更改,所以我會平滑地更新圖表。我無法找到一個線形圖和enter-update-exit邏輯的好例子(或者我看錯了)。目前,我一定要記住,如果圖表被稱爲首次或數據進行更新(數據已經改變) - 這是我的髒版:d3折線圖與輸入更新退出邏輯

var channelGroup = d3.select(".ch1"); 

// init. Line Chart 
    if (firstLoad) { 
    channelGroup 
     .append('path') 
     .attr("class", "line") 
     .style("stroke", channel.Color) 
     .transition() 
     .ease("linear") 
     .duration(animChart/2) 
     .attr('d', line(channel.DataRows)); 
} 
// update Line Chart  
else { 
    channelGroup 
     .selectAll("path") 
     .data([channel.DataRows]) 
     .transition() 
     .ease("linear") 
     .duration(animChart/2) 
     .attr("d", function (d) { return line(d); }); 
} 

我怎麼能在一個良好的方式實現這一點? ... 謝謝!

+0

你見過[此教程](http://www.d3noob.org/2013/02/update-d3js-data-dynamically-button.html)? –

+0

不,謝謝你! – Kollisionskurs

回答

10

你在混合兩種不同的方法,一種是將數據綁定到行,另一種是將數據傳遞給行函數。任何一個都可以工作(只要你只有一行),但是如果你想擺脫你的if/else構造,你仍然需要分離處理輸入/追加元素的語句和語句更新它。

選項1(不綁定數據,只需調用函數):

var linegraph = channelGroup.select('path'); 

if (linegraph.empty()) { 
    //handle the entering data 
    linegraph = channelGroup.append('path') 
         .attr("class", "line") 
         .style("stroke", channel.Color); 
} 

linegraph 
     .transition() 
     .ease("linear") 
     .duration(animChart/2) 
     .attr('d', line(channel.DataRows)); 

選項2(使用數據連接):

var linegraph = channelGroup.selectAll("path") 
     .data([channel.DataRows]); 

linegraph.enter().append('path') 
       .attr("class", "line"); 

linegraph 
     .transition() 
     .ease("linear") 
     .duration(animChart/2) 
     .attr("d", line); //This is slightly more efficient than 
          //function (d) { return line(d); } 
          //and does the exact same thing. 
          //d3 sees that `line` is a function, and 
          //therefore calls it with the data as the 
          //first parameter. 
+0

我已經理解了差異 - 非常感謝您的詳細解釋! – Kollisionskurs

+0

@AmeliaBR:非常感謝! – 2014-07-30 16:45:27

+5

謝謝 - 一直在網上拖網,這是第一個有意義的解釋。真正重要的是要注意''channel.DataRows'在方括號2中是方括號! – RobinL