ChartJS Bar Chart Example

by gautham_myfitapp

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
<div id="container" style="width: 75%;">
<p>
Method 1
</p>
  <canvas id="canvas"></canvas>
</div>
<br/>
<div id="container2" style="width: 75%;">
<p>
Method 2
</p>
  <canvas id="canvas2"></canvas>
</div>

JavaScript

var oMyBarChart;
var ctx = document.getElementById("canvas").getContext("2d");

const labels = ['Capacity', 'Bookings', 'Attendees'];
const data = {
  labels: labels,
  datasets: [{
    axis: 'x',
    data: [50, 30, 20],
    labels: labels,
    backgroundColor: ['red', 'blue', 'green'],
    fill: false,
    borderColor: 'blue',
    borderWidth: 1
  }]
};
const config = {
  type: 'bar',
  data,
  options: {
    scales: {
      xAxes: [{
      	categoryPercentage: 1.0,
        barPercentage: 1.0,
        beginAtZero: true
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true,
          precision: 0
        }
      }]
    },
    responsive: true,
    plugins: {
      labels: {
        render: () => {}
      }
    },
    legend: {
        position: 'top',
        display: true,
        labels: {
          generateLabels: function(chart) {
            let data = chart.data;
            if (data.labels.length && data.datasets.length) {
              return data.labels.map((label, i) => {
                return {
                  text: label
                }
              })
            }
            return [];
          },
        }
      }
  }
};

oMyBarChart = new Chart(ctx, config);


var ctx2 = document.getElementById("canvas2").getContext("2d");
const labels2 = ['Capacity', 'Bookings', 'Attendees'];
const data2 = {
  labels: labels2,
  datasets: [{
      axis: 'x',
      label: 'Capacity',
      data: [50],
      backgroundColor: 'red',
      fill: false,
      borderColor: 'blue',
      borderWidth: 1
    },
    {
      axis: 'x',
      label: 'Bookings',
      data: [30],
      backgroundColor: 'blue',
      fill: false,
      borderColor: 'blue',
      borderWidth: 1
    },
    {
      axis: 'x',
      label: 'Attendees',
      data: [20],
      backgroundColor: 'green',
      fill: false,
      borderColor: 'blue',
      borderWidth: 1
    }
  ]
};
const config2 = {
  type: 'bar',
  data: data2,
  options: {
    scales: {
      xAxes: [{
   ...