[Chartjs]-How to push datasets dynamically for chart.js (bar chart)?

16πŸ‘

βœ…

I don’t think you can use addData to add a series – it’s for adding points / bars to existing series.

However you can insert your new series directly into the chart object. With the chart object and new dataset like so

var ctx = document.getElementById("chart").getContext("2d");
var myBarChart = new Chart(ctx).Bar(data);

var myNewDataset = {
    label: "My Second dataset",
    fillColor: "rgba(187,205,151,0.5)",
    strokeColor: "rgba(187,205,151,0.8)",
    highlightFill: "rgba(187,205,151,0.75)",
    highlightStroke: "rgba(187,205,151,1)",
    data: [48, 40, 19, 86, 27, 90, 28]
}

the code to insert a new dataset would be

var bars = []
myNewDataset.data.forEach(function (value, i) {
    bars.push(new myBarChart.BarClass({
        value: value,
        label: myBarChart.datasets[0].bars[i].label,
        x: myBarChart.scale.calculateBarX(myBarChart.datasets.length + 1, myBarChart.datasets.length, i),
        y: myBarChart.scale.endPoint,
        width: myBarChart.scale.calculateBarWidth(myBarChart.datasets.length + 1),
        base: myBarChart.scale.endPoint,
        strokeColor: myNewDataset.strokeColor,
        fillColor: myNewDataset.fillColor
    }))
})

myBarChart.datasets.push({
    bars: bars
})

myBarChart.update();

Fiddle – http://jsfiddle.net/pvak6rkx/ (inserts the new dataset after 3 seconds)

15πŸ‘

In version 2.x, you can add (or remove) data to the chart directly and then call update(), e.g.

barChart.data.datasets.push({
  label: 'label2',
  backgroundColor: '#ff0000',
  data: [1,2,3]
});
barChart.update();

Here’s a jsfiddle example.

0πŸ‘

Your missing the data key from your chart instance i.e. barChartData.data.datasets.push(e);
No need for any methods. The js chart object data.datasets key accepts an array of objects. Therefore in your case use :

var e = {
         fillColor : "#efefef",
         strokeColor : "#efefef",
         highlightFill: "#efefef",
         highlightStroke: "#efefef",
         data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
            }
barChartData.data.datasets[] = e; // this will append additional data to your chart
barChartData.update();

Just make sure that barChartData is an instance of your js chart.

Leave a comment