2013-09-23 44 views
0

我試圖使用nvd3和d3生成多個圖表。我有適量的div。添加多個圖表d3,nvd3使用for循環

如果我刪除了forloop,那麼我得到一個圖表#chart1。如果我把for循環,然後我得到一個圖表只在#chart2

任何人都可以看到爲什麼?

for (var j = 1; j <= 2; j += 1) { 
    var s = '#chart' + j.toString() + ' svg'; 
    console.log(s); 

    nv.addGraph(function() { 
     var chart = nv.models.lineChart(); 

     chart.xAxis.axisLabel('Time step').tickFormat(d3.format(',r')); 
     chart.yAxis.axisLabel('eig(' + j.toString() + ')').tickFormat(d3.format('.02f')); 
     d3.select(s).datum(function() { 

      var sin = [], cos = []; 
      for (var i = 0; i < 100; i++) { 
       sin.push({ 
        x : i, 
        y : Math.sin(i/10) 
       }); 
       cos.push({ 
        x : i, 
        y : .5 * Math.cos(i/10) 
       }); 
      } 

      result = []; 
      result.push({ 
       values : sin, 
       key : 'sin', 

      }); 

      return result; 
     }).transition().duration(500).call(chart); 

     nv.utils.windowResize(chart.update); 
     return chart; 
    }); 
} 

回答

2

首先,它不是普通就像你有(數據驅動文件)使用一個for循環。在D3最好是選擇你想要的所有元素,並使用.each()像這樣

d3.selectAll('.chart svg') 
    .each(function(data){ 
     // Do what you would have done in the loop here 
}) 

其次,它看起來像有使用匿名函數你的方式(不知道的問題,爲什麼不花太多時間看)。通過將其稱爲實際功能,它可以工作。

nv.addGraph(addMyChart(this)) 

看到這個的jsfiddle http://jsfiddle.net/a5BYP/