[Chartjs]-Chart.js changes selected legend filters when using update function

3๐Ÿ‘

โœ…

Iโ€™m not a fan of combined charts and data. I want data and options as separate variables. Then your update() works as a charm and is much shorter and easier to read.
JSBin with all the code

var chartOptions = {
    scales: {
        xAxes: [{
            stacked: true
        }],
        yAxes: [{
            stacked: true
        }]
    }
}

var chartData = {
    labels: ["First", "Second", "Third", "Fourth"],
    datasets: [{
        label: 'First',
        data: [12, 19, 3, 5],
        backgroundColor: 'red'
    },{
        label: 'Second',
        data: [5, 19, 3, 5],
        backgroundColor: 'blue'
    },{
        label: 'Third',
        data: [8, 19, 3, 5],
        backgroundColor: 'green'
    },{
        label: 'Fourth',
        data: [9, 19, 3, 5],
        backgroundColor: 'orange'
    }]
}

var ctx = document.getElementById("myChart");
var stackedBar = new Chart(ctx, {
    type: 'bar',
    data: chartData,
    options: chartOptions
});

function updateChart() {
    chartData.datasets.forEach(function(element) {
        element.data = r();
    });
    stackedBar.update();
}

function r() {
    var values = [];
    for (i = 0; i < 4; i++) { 
        values.push(Math.floor(Math.random() * 100) + 1);
    }
    return values;
}

Leave a comment