score:1

Accepted answer

Your current code is supplying the same data variable each time you create a chart. Below is an example of switching between two completely different charts by providing different configuration options to the Chart constructor.

let lineConfig = {
    type: 'line',
    data: {
      labels: ['q', 'w', 'e', 'r', 't', 'y'],
      datasets: [{
        data: [6, 5, 4, 3, 2, 1]
      }]
    }
  },
  barConfig = {
    type: 'bar',
    data: {
      labels: ['a', 's', 'd', 'f', 'g', 'h'],
      datasets: [{
        data: [10, 20, 30, 40, 50, 60]
      }]
    }
  },
  activeType = 'bar', // we'll start with a bar chart.
  myChart;

function init(config) {
  // create a new chart with the supplied config.
  myChart = new Chart(document.getElementById('chart'), config);
}

// first init as a bar chart.
init(barConfig);

document.getElementById('switch').addEventListener('click', function(e) {
  // every time the button is clicked we destroy the existing chart.
  myChart.destroy();
  if (activeType == 'bar') {
    // chart was a bar, init a new line chart.
    activeType = 'line';
    init(lineConfig);
    return;
  }

  // chart was a line, init a new bar chart.
  activeType = 'bar';
  init(barConfig);
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>
<button id="switch">Switch</button>


Related Query

More Query from same tag