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