Chart JS : Update Bar Chart

This jsfiddle demonstrates how to create a bar chart using chart js library and update it with different values in every second.

by cubicalmonkey

HTML

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>
<body>
    <div>
        <h1>Update Bar Chart</h1>
        <canvas id="barChart" width="800" height="450"></canvas>
    </div>
    <script src="barchart.js"></script>
</body>
</head>
</html>

JavaScript

//value for x-axis
var emotions = ["calm", "happy", "angry", "disgust"];

//colours for each bar
var colouarray = ['red', 'green', 'yellow', 'blue'];

//Let's initialData[] be the initial data set
var initialData = [0.1, 0.4, 0.3, 0.6];

//Let's updatedDataSet[] be the array to hold the upadted data set with every update call
var updatedDataSet;

/*Creating the bar chart*/
var ctx = document.getElementById("barChart");
var barChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: emotions,
        datasets: [{
            backgroundColor: colouarray,
            label: 'Prediction',
            data: initialData
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    min: 0,
                    max: 1,
                    stepSize: 0.5,
                }
            }]
        }
    }
});

/*Function to update the bar chart*/
function updateBarGraph(chart, label, color, data) {
    chart.data.datasets.pop();
    chart.data.datasets.push({
        label: label,
        backgroundColor: color,
        data: data
    });
    chart.update();
}

/*Updating the bar chart with updated data in every second. */
setInterval(function () {
	var x = new Date();
  	emotions.push(x);
    initialData.push ( Math.random() );
		//updatedDataSet = [Math.random(), Math.random(), Math.random(), Math.random()];
    updateBarGraph(barChart,'Prediction', colouarray, initialData);
  }, 1000);