Dynamic Changing of Chart Type for Line chart to Bar chart - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Dynamic Changing of Chart Type for Line chart to Bar chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.1/Chart.bundle.min.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){// w  ww . j  a va  2s. c  o  m
var config = {
  type: 'line',
  data: {
    labels: ["June", "July", "August", "September", "October", "November", "December"],
    datasets: [{
      label: "company1",
      data: [1, 1, 2, 3, 4, 5, 6],
      fill: false,
      borderColor: "purple",
      backgroundColor: "purple"
    }, {
      label: "company2",
      data: [1, 2, 4, 8, 3, 2, 4],
      fill: false,
      borderColor: "green",
      backgroundColor: "green"
    }]
  },
  options: {
    responsive: true,
  }
};
var myChart;
$("#line").click(function() {
  change('line');
});
$("#bar").click(function() {
  change('bar');
});
function change(newType) {
  var ctx = document.getElementById("canvas").getContext("2d");
  // Remove the old chart and all its event handles
  if (myChart) {
    myChart.destroy();
  }
  // Chart.js modifies the object you pass in. Pass a copy of the object so we can use the original object later
  var temp = jQuery.extend(true, {}, config);
  temp.type = newType;
  myChart = new Chart(ctx, temp);
};
    }

      </script> 
   </head> 
   <body> 
      <button id="line">line</button> 
      <button id="bar">bar</button> 
      <canvas id="canvas"></canvas>  
   </body>
</html>

Related Tutorials