[Chartjs]-How to set labels align left in Horizontal Bar using chart.js?

7👍

The yAxis.ticks labels can be left aligned by defining mirror: true combined with adding some padding.

yAxes: [{
  ticks: {
    mirror: true,
    padding: 220
  },

To make the labels visible on the chart area, the same padding needs to be defined left of the chart layout.

layout: {
  padding: {
    left: 220
  }
},

Please have a look at your changed code below.

new Chart('myChart', {
  type: 'horizontalBar',
  data: {
    labels: ["Total", "301 Redirect", "Broken Pages (4xx Errors)", "Uncategorised HTTP Response Codes", "5xx Errors", "Unauthorised Pages", "Non-301 Redirects"],
    datasets: [{
      data: [16, 14, 1, 1, 0, 0, 0],
      backgroundColor: ['rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)', 'rgba(237, 56, 98, 1.0)','rgba(237, 56, 98, 1.0)']
    }]
  },
  options: {
    responsive: false,
    layout: {
      padding: {
        left: 220
      }
    },  
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          mirror: true,
          padding: 220
        },
        gridLines: {
          display: false
        },
      }],
      xAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          drawBorder: false,
        }
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="500" height="200"></canvas>

6👍

You can control labels alignment by using crossAlignment option on the tick configuration. There are three possible values: "near", "center", and "far".

In your case, you will just use near

options: {
...
  scales: {
    y: {
      ticks: {
        crossAlign: "far",
      },
    },
  },
}

Leave a comment