chart.js dynamically add y axes from json - Javascript Chart.js

Javascript examples for Chart.js:Chart Json Data

Description

chart.js dynamically add y axes from json

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>ChartJS new y axe (update)</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script> 
      <style id="compiled-css" type="text/css">

canvas { background-color : #eee;
}


      </style> 
      <script type="text/javascript">
    window.onload=function(){/*from   w w  w.j  a  v  a2  s.c om*/
var config = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
       {
         label: '# of Votes',
         data: [12, 19, 3, 5, 2, 3],
        lineTension: 0.1,
         borderWidth: 1,
        borderWidth: 3,
        borderColor: 'red',
       },
      ]
  },
  options: {
     scales: {
       yAxes: [{
         id: "y-axis-1",
        display: true,
        position: "left",
        ticks: {
               reverse: false
        }
      },
      {
         id: "y-axis-2",
        display: false,
        position: "right",
      }]
    }
  }
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
var chart = new Chart(ctx, config);
// WORKING
addNewYAxe = function() {
  var y2 = chart.options.scales.yAxes[1];
  y2.type = "linear";
  y2.display = true;
  chart.update();
}
// NOT WORKING
addNewYAxe2 = function() {
  chart.options.scales.yAxes.pop();
  chart.options.scales.yAxes.push({
    type: "linear",
    display: true,
    position: "right",
    id: "y-axis-2",
    gridLines: {
      drawOnChartArea: false,
    },
  });
  chart.update();
}
    }

      </script> 
   </head> 
   <body> 
      <button onclick="addNewYAxe()">add new Y axe</button> 
      <button onclick="addNewYAxe2()">add new Y axe 2</button> 
      <canvas id="chartJSContainer" width="600" height="400"></canvas>  
   </body>
</html>

Related Tutorials