Is it possible to show each legends aligned with each bar in chart.js

967 Views Asked by At

I made a horizontal bar chart using Chart.js. In default setting all the legends are shown all together like this

enter image description here

there is no gap among them. I want to show each legend aligned with each bar like this

enter image description here

I tried so many solutions but none of them worked. Is it possible to show legends right and center aligned with each bar in chart.js?

I am using Chart.js (v.3.7)

1

There are 1 best solutions below

6
On

The behavior you are looking for can possibly be achieved by using the padding option in the Legend Label Configuration and trying to find the correct value. This could look something like this:

const chart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        plugins: {
            legend: {
                display: true,
                labels: {
                    padding: 15 // change according to testing
                }
            }
        }
    }
});
 

You would usually not use a legend for this but instead label the axis directly as described in the link below.

Have a look at the documentation: https://www.chartjs.org/docs/latest/axes/cartesian/#tick-configuration

It provides an example on how to use axis labels like that:

// config
const config = {
  type: 'bar',
  data,
  options: {
    indexAxis: 'y',
    scales: {
      y: {
        ticks: {
          crossAlign: 'far',
        }
      }
    }
  }
};

// setup
const labels = ["Label 1", "Label 2", "Label 3"]
const data = {
  labels: labels,
  datasets: [{
    label: 'My dataset',
    borderWidth: 1,
    data: [65, 59, 80],
  }]
};