Chartjs-Chart js 2.8 – How to make bars grow at the same speed?

0πŸ‘

I don’t know if there is a better way to do it, but the simplest thing I could think of is to update the dataset according to our needs.

Initially, we can keep all data elements equal and then gradually change them as we want.

Here is a simple solution that I managed to code link.

var canvas = document.getElementById('myChart');
var dataPoints = [65, 59, 30, 81, 56, 55, 40];
var chartData = [];
chartData.length = dataPoints.length;
chartData.fill(nthSmallest(dataPoints, 1));
var doNotOverwrite = [dataPoints.indexOf(chartData[0])];

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: chartData,
        }
    ]
};

var myBarChart = Chart.Bar(canvas,{
    data:data,
  options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true,
                suggestedMax: Math.max(...dataPoints)
            }
        }]
    }
}
});

var index = 0;

var interval = setInterval(()=> {
  index++;

  var num = nthSmallest(dataPoints, index);
  appendArray(num);
  doNotOverwrite.push(dataPoints.indexOf(chartData[0]));
  myBarChart.update();
  if(index == dataPoints.length) {
    clearInterval(interval);
  }
}, 1000);

function appendArray(num) {
            for(let i = 0; i< chartData.length; i++) {
        if(!doNotOverwrite.includes(i)) {
            chartData[i] = num;
        }
      }
}

function nthSmallest(numbers, n) {
        numbers = JSON.parse(JSON.stringify(numbers));
    var sorted = numbers.sort(function (a, b) {
        return b - a;
    });
    return sorted[sorted.length - n];
}

I wrote it in a hurry, so there might be some issues with the code. (Array with repetitive elements will not work as I am using index).

You will also need to update your options for it to work properly.

I know it is not the prettiest solution, but hey it works. πŸ™‚

Leave a comment