ChartJS bar chart with fixed width for dynamic data sets - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

ChartJS bar chart with fixed width for dynamic data sets

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.6.0/Chart.bundle.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//from w  w w.  j  a  v  a2 s  .c o  m
var barChartData1 = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: 'Dataset 1',
    data: [3,2,7,4,5,7,6]
  }, {
    label: 'Dataset 2',
    backgroundColor: "#faa",
    data: [11,13,21,13,16,21,18]
  }]
};
var barChartData2 = {
  labels: ["January"],
  datasets: [{
    label: 'Dataset 1',
    data: [6]
  }, {
    label: 'Dataset 2',
    backgroundColor: "#faa",
    data: [11]
  }]
};
var ctx1 = document.getElementById("canvas1").getContext("2d");
var ctx2 = document.getElementById("canvas2").getContext("2d");
var myBar1 = new Chart(ctx1, {
  type: 'bar',
  data: barChartData1,
  options: {
    responsive: true,
    scales: {
      xAxes: [{
          barPercentage: 1,
          categoryPercentage: 0.5 / 10 * barChartData1.datasets[0].data.length
      }],
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});
var myBar2 = new Chart(ctx2, {
  type: 'bar',
  data: barChartData2,
  options: {
    responsive: true,
    scales: {
      xAxes: [{
          barPercentage: 1,
          categoryPercentage: 0.5 / 10 * barChartData2.datasets[0].data.length
      }],
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="canvas1"></canvas> 
      <canvas id="canvas2"></canvas>  
   </body>
</html>

Related Tutorials