Chartjs-How to dynamicly change the json data in chartjs

0๐Ÿ‘

โœ…

var ctx = document.getElementById("myChart").getContext('2d');
var myData = [1, 3, 5, 7, 10, 15];

        var myChart = new Chart(ctx, {
            type: 'bar',
            data: { 
                labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                datasets: [{
                    label: '# of Votes',
                    data: myData,
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.5)',
                        'rgba(54, 162, 235, 0.5)',
                        'rgba(255, 206, 86, 0.5)',
                        'rgba(75, 192, 192, 0.5)',
                        'rgba(153, 102, 255, 0.5)',
                        'rgba(255, 159, 64, 0.5)'
                    ],
                    borderColor: [
                        'rgba(255,99,132,1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }]
                }
            }
        });
        function updateData(chart, labels, mydata) {
            //if(labels) chart.data.labels = labels;
            //chart.data.datasets.forEach((dataset) => {
            //    dataset.data[0]++; // Or you can cheng data like this
            //});
            chart.update();
        }
        setInterval(function(){
          myData[0]++;
          updateData(myChart,null,myData); 
        },1000);
<div style="width: 500px; height: 500px">
        <canvas id="myChart" width="400" height="400" style="width: 400px !important"></canvas>
    </div>
    <script src="http://www.chartjs.org/dist/2.7.2/Chart.bundle.js"> </script>

Leave a comment