Skip to content

Instantly share code, notes, and snippets.

@amelieykw
Last active May 29, 2018 08:23
Show Gist options
  • Save amelieykw/f19a09fca5c96efd7706430f0205eab3 to your computer and use it in GitHub Desktop.
Save amelieykw/f19a09fca5c96efd7706430f0205eab3 to your computer and use it in GitHub Desktop.
[ChartJS | Updating Charts] #ChartJS

Adding and removing data is supported by changing the data array. To add data, just add data into the data array as seen in this example.

function addData(chart, label, data) {
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}

function removeData(chart) {
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
        dataset.data.pop();
    });
    chart.update();
}

To update the options, mutating the options property in place or passing in a new options object are supported.

  • If the options are mutated in place, other option properties would be preserved, including those calculated by Chart.js.
  • If created as a new object, it would be like creating a new chart with the options - old options would be discarded.
function updateConfigByMutating(chart) {
    chart.options.title.text = 'new title';
    chart.update();
}

function updateConfigAsNewObject(chart) {
    chart.options = {
        responsive: true,
        title:{
            display:true,
            text: 'Chart.js'
        },
        scales: {
            xAxes: [{
                display: true
            }],
            yAxes: [{
                display: true
            }]
        }
    }
    chart.update();
}

Scales can be updated separately without changing other options. To update the scales, pass in an object containing all the customization including those unchanged ones.

Variables referencing any one from chart.scales would be lost after updating scales with a new id or the changed type.

function updateScales(chart) {
    var xScale = chart.scales['x-axis-0'];
    var yScale = chart.scales['y-axis-0'];
    chart.options.scales = {
        xAxes: [{
            id: 'newId',
            display: true
        }],
        yAxes: [{
            display: true,
            type: 'logarithmic'
        }]
    }
    chart.update();
    // need to update the reference
    xScale = chart.scales['newId'];
    yScale = chart.scales['y-axis-0'];
}

You can also update a specific scale either by specifying its index or id.

function updateScale(chart) {
    chart.options.scales.yAxes[0] = {
        type: 'logarithmic'
    }
    chart.update();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment