Dynamically update values of a chartjs chart

2019-01-04 17:08发布

I created an basic bar chart using chartjs and it works fine. Now I want to update the values on a time based interval. My problem is that after I created the chart, I do not know how to update its values correctly...

My code:

var ctx = $("#myChart").get(0).getContext("2d");

var dts = [
    {
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,1)",
        data: [0, 0, 0, 0, 0]
    }
];

var data = {
    labels: ["Core#1", "Core#2", "Core#3", "Core#4", "Total"],
    datasets: dts
};

var chart = new Chart(ctx);
chart.Bar(data);

//test code
setInterval( function () {                        
    data.datasets[0].data = [random(), random(), random(), random(), random()];
    chart.Bar(data);

},2000);

in the test code, I am updating the values with datasets[0].data- is this the right way to do it? The problem with this is that everytime I call chart.Bar(), the values are reset to 0 then animated to the random value (like I am recreating the chart). This way, all animations are always from 0 to value which looks strange. I would expect that if I update a value from 50 to 10 the bar would go down to 10 from 50 and not setted to 0 then animated to 10.

I did not found anything in the docs about this... am I doing something wrong or this is impossible with this library?

10条回答
来,给爷笑一个
2楼-- · 2019-01-04 17:28

Remove the canvas dom and add in again.

function renderChart(label,data){

    $("#canvas-wrapper").html("").html('<canvas id="storeSends"></canvas>');
    var lineChartData = {
        labels : label,
        datasets : [
            {
                fillColor : "rgba(49, 195, 166, 0.2)",
                strokeColor : "rgba(49, 195, 166, 1)",
                pointColor : "rgba(49, 195, 166, 1)",
                pointStrokeColor : "#fff",
                data : data
            }
        ]

    }
    var canvas = document.getElementById("storeSends");
    var ctx = canvas.getContext("2d");

    myLine = new Chart(ctx).Line(lineChartData, {
        responsive: true,
        maintainAspectRatio: false
    });
}
查看更多
The star\"
3楼-- · 2019-01-04 17:29

So simple, Just replace the chart canvas element.

$('#canvas').replaceWith(' id="canvas" height="200px" width="368px">');

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-04 17:32

The simplest way is to replace the canvas element and then call new Chart() again:

function reloadMyChart() {
    $('myChart').replaceWith('<canvas id="myChart"></canvas>');
    new Chart(document.getElementById("myChart"), {
        data: yourChartData,
        type: yourChartType,
        options: yourChartOptions
    });
}

Of course, you must replace yourChartData, yourChartType and yourChartOptions with the correct values required to initialize Chart.js. See Chart.js Docs.

You can call reloadMyChart function on a button click or any other event you need. Probably you'll add parameters to this function and use these to make a REST call to dynamically update your chart, like this:

function reloadMyChart(param1, param2) {
    $('myChart').replaceWith('<canvas id="myChart"></canvas>');
    $.get("restUrl?param1=" + param1 + "&param2=" + param2 + ",
        function(data) {
            // call new Chart() here and use returned data
        }
    );

Hope it helps! =)

查看更多
The star\"
5楼-- · 2019-01-04 17:34

I don't think it's possible right now.

However that's a feature which should come soon, as the author hinted here: https://github.com/nnnick/Chart.js/issues/161#issuecomment-20487775

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-04 17:34

If destroy() and clear() is not working (just like what i had experience) you can use jquery to remove the canvas and append it again.

    $('#chartAmazon').remove();
    $('#chartBar').append('<canvas id="chartAmazon"></canvas>');

    var ctxAmazon = $("#chartAmazon").get(0).getContext("2d");
      var AmazonChart = new Chart(ctxAmazon, {
        type: 'doughnut',
        data: dataAmazon,
        options: optionsA
    });
查看更多
聊天终结者
7楼-- · 2019-01-04 17:35

Here is how to do it in the last version of ChartJs:

setInterval(function(){
    chart.data.datasets[0].data[5] = 80;
    chart.data.labels[5] = "Newly Added";
    chart.update();
}

Look at this clear video

or test it in jsfiddle

查看更多
登录 后发表回答