[Chartjs]-Chart.js pie chart – how to update dataset with smooth transition

3👍

You override the entire dataset, if you instead of doing that only change the data of that dataset it will shrink/expand the segments of the data.

Example:

const options = {
  type: 'pie',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      }
    ]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);

document.getElementById('update').addEventListener('click', () => {
  chart.data.datasets[0].data = [10, 5, 12, 6, 8, 2];
  chart.update();
})
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <button id="update">
      update data
    </button>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>

Leave a comment