Using a JavaScript array we can update values and update the chart to replicate a live graph as we input new data.
In this example we will create an update button that will add random numbers to the array.
Start with a basic graph template
Within our script lets create two global arrays called data and count. And lets assign some values.
//create two global variables
var count = [0,1,2,3,4];
var data = [2,4,5,6,8];
Replace the static numbers and labels in the graph.js data object with the new arrays.
data: {
labels: count ,
datasets: [{
label: '# of Votes',
data: data,
Now we can write a function to add a random number to the data array and add one to the next count in the array called count.
We also need to force the update of the graph. - myChart.update();
function updateGraph(){
data.push(Math.round(Math.random()*100));
count.push(count.length);
myChart.update();
}
Lets add a button to the html code so that when clicked the graph updates
<button onClick="updateGraph()">Update</button>
var ctx = document.getElementById('myChart').getContext('2d');
//create two global variables
var count = [0,1,2,3,4];
var data = [2,4,5,6,8];
function updateGraph(){
data.push(Math.round(Math.random()*100));
count.push(count.length);
myChart.update();
}
var myChart = new Chart(ctx, {
type: 'bar', //pie,line
data: {
labels: count ,
datasets: [{
label: '# of Votes',
data: data,
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'y-axis'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'X axis'
}
}]
}
}
});
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
</head>
<style>
#layout {
width: 400px;
height: 400px;
}
</style>
<body>
<button onClick="updateGraph()">Update</button>
<div id="layout">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<script src = "script.js"></script>
</body>
</html>