Chartjs-Update chartjs chart within random data once per second

0👍

Right now you’re adding an extra slot to the dataset (you need to have the same amount of labels as data in the dataset, so if you want to add more data – also add more labels) – try replacing a data instead, like:

    $(document).ready(function () {

        var canvas1 = document.getElementById('myChart1');
        var data = {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [
                {
                    label: "My First dataset",
                    fill: false,
                    lineTension: 0.1,
                    backgroundColor: "rgba(75,192,192,0.4)",
                    borderColor: "rgba(75,192,192,1)",
                    borderCapStyle: 'butt',
                    borderDash: [],
                    borderDashOffset: 0.0,
                    borderJoinStyle: 'miter',
                    pointBorderColor: "rgba(75,192,192,1)",
                    pointBackgroundColor: "#fff",
                    pointBorderWidth: 1,
                    pointHoverRadius: 5,
                    pointHoverBackgroundColor: "rgba(75,192,192,1)",
                    pointHoverBorderColor: "rgba(220,220,220,1)",
                    pointHoverBorderWidth: 2,
                    pointRadius: 5,
                    pointHitRadius: 10,
                    data: [65, 59, 80, 0, 56, 55, 40],
                }
            ]
        };
        


        function adddata() {

            setInterval(function () {
                let randomIndex = Math.floor(Math.random() * Math.floor(myLineChart.data.datasets[0].data.length));
                myLineChart.data.datasets[0].data[randomIndex] = Math.floor(Math.random() * 100);
                myLineChart.update();
            }, 1000)

        }
        
        var myLineChart = Chart.Line(canvas1, {
            data: data,
            options: option
        });

        var option = {
            showLines: true
        };


adddata();

    });
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>


<div class="chart-container" style="position: absolute; height:20vh; width:40vw">
    <canvas id="myChart1"></canvas>
    <input onclick="adddata()" type="button" value="Add Data">
</div>

You can read more about in the documentation: https://www.chartjs.org/docs/latest/developers/updates.html

Leave a comment