[Chartjs]-Create bar chart with chart.js where space per bar is the same, overall chart size adjusted

1👍

The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the beforeRender hook to define the height of the canvas parent div depending on the number of bars contained in the chart. This function must also consider the space needed on top and below the chart, especially for drawing the xAxis ticks.

plugins: [{
  beforeRender: chart => {
    if (!chart.config.options.nonChartAreaHeight) {
      var yAxis = chart.scales['y-axis-0'];
      chart.config.options.nonChartAreaHeight = chart.chart.height - (yAxis.bottom - yAxis.top);
    }
    const barThickness = chart.config.data.datasets[0].barThickness;
    const chartAreaHeight = (chart.config.data.labels.length * barThickness * 2);
    document.getElementById("chartWrapper").style.height = (chartAreaHeight + chart.config.options.nonChartAreaHeight) + 'px';
  }
}],

Please note that instead of defining the option aspectRatio, we need to define maintainAspectRatio: false.

Please have a look at the code sample below that produces two charts. This solution uses the latest stable version of Chart.js (2.9.3).

new Chart('myChart', {
  type: 'horizontalBar',
  plugins: [{
    beforeRender : chart => {        
      if (!chart.config.options.nonChartAreaHeight) {
        var yAxis = chart.scales['y-axis-0'];
        chart.config.options.nonChartAreaHeight = chart.chart.height - (yAxis.bottom - yAxis.top);
      }
      const barThickness = chart.config.data.datasets[0].barThickness;
      const chartAreaHeight = (chart.config.data.labels.length * barThickness * 2);
      document.getElementById("chartWrapper").style.height = (chartAreaHeight + chart.config.options.nonChartAreaHeight) + 'px';      
    }
  }],
  data: {
    labels: ['1', '2', '3', '4'],
    datasets: [{
      barThickness: 20,
      data: [100, 90, 80, 70]
    }]
  },
  options: {
    maintainAspectRatio: false,
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
div {  
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div id="chartWrapper">
  <canvas id="myChart"></canvas>
</div>

Leave a comment