[Chartjs]-ChartJs: HorizontalBar Missing Background Colours

1👍

I cannot tell why your code is not working but can propose a different approach to solve the problem.

Please have a look at your amended code below. In order to get rid of annoying JavaScript warnings, I use the latest stable versio nof Chart.js (2.3.0).

I included two bars since I expect that the data can be of dynamic size. It should however also work for a single bar. I didn’t know however what to do with the y value, this depends on your use case.

$(() => {
  var data = [{
    l: 'ABC',
    t: '2015-3-15',
    y: 10
  }, {
    l: 'XYZ',
    t: '2020-11-05',
    y: 20
  }];
  var ctx = $("#Chart")[0];
  var chart = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
      yLabels: data.map(o => o.l),
      datasets: [{
        label: 'ABC',
        data: data.map(o => moment(o.t, 'YYYY-M-DD')),
        backgroundColor: ['rgba(255,0,0, 0.5)', 'rgba(0,255,0,0.5)']
      }]
    },
    options: {
      legend: {
        display: false
      },
      scales: {
        xAxes: [{
          type: 'time',
          time: {
            parser: 'YYYY-M-DD',
            unit: 'year',
            tooltipFormat: 'YYYY/M/D'
          },
          ticks: {
            min: '2010-1-01',
            max: '2030-1-01'
          }
        }]
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

<canvas id="Chart" height="80"></canvas>

Leave a comment