theKing
theKing

Reputation: 844

ChartJS: Horizontal Bar with multiple datasets not showing Bars

I have Horizontal Bar comparing Rooms & Guests target vs achieved. Rooms has 3 data values (Available, Budget, Actual) and Guests has only 2 (Budget, Actual).

Below is the code generates the chart:

 data = [{
        label: 'Available',
        backgroundColor: '#3366ff',
        data: [5580]
    }, {
        label: 'Budget',
        backgroundColor: '#009999',
        data: [5000, 6500]
    }, {
        label: 'Actual',
        backgroundColor: '#92d400',
        data: [5200, 7245]
    }];

 var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
        labels: ["Rooms", "Guests"],
        datasets: data
    }
}

Issue with the above code is, Rooms Budget bar is not showing up.

It shows only when I add [5580,0] to the Guests Available data value; however there is no such Data for Guests like Rooms.

Here is the JSFiddle (https://jsfiddle.net/kingBethal/vtf17k84/8/).

Upvotes: 2

Views: 7235

Answers (1)

timclutton
timclutton

Reputation: 13004

5000 is the lowest value in your dataset and Chart.js is creating its scale starting at 5000:

enter image description here

Set the beginAtZero property to true and you'll see the expected bar:

let data = [{
  label: 'Available',
  backgroundColor: '#3366ff',
  data: [5580]
}, {
  label: 'Budget',
  backgroundColor: '#009999',
  data: [5000, 6500]
}, {
  label: 'Actual',
  backgroundColor: '#92d400',
  data: [5200, 7245]
}];

let myChart = new Chart(document.getElementById('chart'), {
  type: 'horizontalBar',
  data: {
    labels: ["Rooms", "Guests"],
    datasets: data
  },
  options: {
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>

Upvotes: 3

Related Questions