0

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)

Alien
  • 121
  • 1
  • 1
  • 11

1 Answers1

-1

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],
  }]
};
Vincent
  • 482
  • 4
  • 15
  • In this document did not show nay usages of the legend. Or I couldn't get what you said. Would you please elaborate? – Alien Apr 26 '22 at 20:36
  • Have a look at the section called Tick Alignment, the link sometimes doesn't directly jump to it unfortunately. As I said, you would not use the legend for this and instead use the axis ticks to achieve the look you want. – Vincent Apr 26 '22 at 20:39
  • No, I have to use the legend not the axis ticks. I just need space among legends so that they get aligned with each bar – Alien Apr 27 '22 at 06:49
  • @Chris As no initial code to go off was provided, what is one supposed to do when trying to refer to the official documentation? – Vincent Apr 27 '22 at 10:24
  • @Chris I see. This makes sense. I'll update my answer accordingly. – Vincent Apr 27 '22 at 11:04
  • @Alien maybe have a look at my updated answer. :) – Vincent Apr 27 '22 at 11:41