Chartjs-How to creat a dynamic datasets and new dynamic multi yAxes

0👍

The problem is with chart.js version. If you update to latest (2.9.3) the issue is resolved.

function rdnum() {
  return Math.floor(Math.random() * 100);
}

var config = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: []
  },
  options: {
    scales: {
      yAxes: []
    }
  }
}
var i = 0;
var x;

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


addNewYAxe = function() {
  x = Date.now();

  let newDataset = {
    label: 'test' + '_' + i,
    data: [],
    yAxisID: "left" + x,
    fill: false
  };
  for (let index = 0; index < 6; ++index) {
    newDataset.data.push(rdnum());
  }

  chart.data.datasets[i] = newDataset;
  //chart.data.datasets.push(newDataset);

  console.log(chart.data.datasets);

  let y = {};
  chart.options.scales.yAxes[i] = y;
  //chart.options.scales.yAxes.push(y);

  let y2 = chart.options.scales.yAxes[i];
  y2.display = true;
  y2.type = "linear";
  y2.id = "left" + x;
  y2.position = "right";
  i++;

  console.log(chart.options.scales.yAxes);

  chart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addNewYAxe()">add new Y axe</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>

Leave a comment