Updating Charts

It's pretty common to want to update charts after they've been created. When the chart data or options are changed, Chart.js will animate to the new data values and options.

Adding or Removing Data

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.

  1. function addData(chart, label, data) {
  2. chart.data.labels.push(label);
  3. chart.data.datasets.forEach((dataset) => {
  4. dataset.data.push(data);
  5. });
  6. chart.update();
  7. }
  8. function removeData(chart) {
  9. chart.data.labels.pop();
  10. chart.data.datasets.forEach((dataset) => {
  11. dataset.data.pop();
  12. });
  13. chart.update();
  14. }

Updating Options

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.
  1. function updateConfigByMutating(chart) {
  2. chart.options.title.text = 'new title';
  3. chart.update();
  4. }
  5. function updateConfigAsNewObject(chart) {
  6. chart.options = {
  7. responsive: true,
  8. title:{
  9. display:true,
  10. text: 'Chart.js'
  11. },
  12. scales: {
  13. xAxes: [{
  14. display: true
  15. }],
  16. yAxes: [{
  17. display: true
  18. }]
  19. }
  20. }
  21. chart.update();
  22. }

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.

  1. function updateScales(chart) {
  2. var xScale = chart.scales['x-axis-0'];
  3. var yScale = chart.scales['y-axis-0'];
  4. chart.options.scales = {
  5. xAxes: [{
  6. id: 'newId',
  7. display: true
  8. }],
  9. yAxes: [{
  10. display: true,
  11. type: 'logarithmic'
  12. }]
  13. }
  14. chart.update();
  15. // need to update the reference
  16. xScale = chart.scales['newId'];
  17. yScale = chart.scales['y-axis-0'];
  18. }

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

  1. function updateScale(chart) {
  2. chart.options.scales.yAxes[0] = {
  3. type: 'logarithmic'
  4. }
  5. chart.update();
  6. }

Code sample for updating options can be found in toggle-scale-type.html.

Preventing Animations

Sometimes when a chart updates, you may not want an animation. To achieve this you can call update with a duration of 0. This will render the chart synchronously and without an animation.