2016-04-13 3 views
1

私は、ChartJSを使用して生成された2つの棒グラフが必要です。 何らかの理由で、上部と下部のグラフが同じラベルを共有していますか?2つのチャートが同じラベルを繰り返しているのはなぜですか?

var data = { 
     labels: [], 
     datasets: [ 
      { 
       fillColor: "rgba(151,187,205,0.5)", 
       strokeColor: "rgba(151,187,205,0.8)", 
       highlightFill: "rgba(151,187,205,0.75)", 
       highlightStroke: "rgba(151,187,205,1)" 
      } 
     ] 
    }; 
    var options = { 
     animation: true, 
     responsive: true 
    }; 


    var ctx1 = document.getElementById("february-chart").getContext("2d"); 
    februaryChart = new Chart(ctx1).Bar(data, options); 

    var ctx2 = document.getElementById("march-chart").getContext("2d"); 
    marchChart = new Chart(ctx2).Bar(data, options); 


    februaryChart.addData([2], 'aaaa'); 
    marchChart.addData([5], 'bbbb'); 

https://jsfiddle.net/4tg2uvc6/

+2

私は 'addData'方法は、あなたがデータとして渡す変数が更新されると思います。両方のチャートで使用されているので、両方とも更新されます。これはちょうど投機ですが、この[フィドル](https://jsfiddle.net/4tg2uvc6/1/)はそれを確認しているようです – ste2425

答えて

2

それらが同じデータオブジェクトへの参照を共有しているので。 addDataメソッドを呼び出すと、両方とも同じオブジェクトが変更されます。各インスタンスに異なるデータオブジェクトを提供しますが、それらを同じにしたい場合は、引き続きオプションを共有できます。

​​

var marchData = { 
    labels: [], 
    datasets: [ 
     { 
      fillColor: "rgba(151,187,205,0.5)", 
      strokeColor: "rgba(151,187,205,0.8)", 
      highlightFill: "rgba(151,187,205,0.75)", 
      highlightStroke: "rgba(151,187,205,1)" 
     } 
    ] 
}; 
var febData = { 
    labels: [], 
    datasets: [ 
     { 
      fillColor: "rgba(151,187,205,0.5)", 
      strokeColor: "rgba(151,187,205,0.8)", 
      highlightFill: "rgba(151,187,205,0.75)", 
      highlightStroke: "rgba(151,187,205,1)" 
     } 
    ] 
}; 
var options = { 
    animation: true, 
    responsive: true 
}; 



var ctx1 = document.getElementById("february-chart").getContext("2d"); 
februaryChart = new Chart(ctx1).Bar(febData, options); 

var ctx2 = document.getElementById("march-chart").getContext("2d"); 
marchChart = new Chart(ctx2).Bar(marchData, options); 


februaryChart.addData([2], 'aaaa'); 
marchChart.addData([5], 'bbbb'); 
+0

感謝、感謝! –

+0

心配、幸運。 – Yoda

関連する問題