Chartjs-Chart.js – How can i add a legend?

0👍

I am not sure what you mean by ‘legend for each bar’ but I’m guessing what you want to do is replace the numbers with text.

You can have an object that holds key value pairs so that effectively each number corresponds to a word.

Then you have to specify a custom label with logic that parses the number to its word.

You can do that using scales and ticks in ChartJS

This is your key value pair object:

var xLabels = {
    1 : 'HELLO',
    2 : 'THERE',
    3 : 'MY',
    4 : 'FRIEND'
}

And this is what the options will have to look like:

 options: {
   scales: {
     xAxes: [{
       ticks: {
         callback: function (value, index, values) {
           return xLabels[value];
         }
       }
     }]
   }
 }

Here is a fiddle example:

https://jsfiddle.net/7dxp2qzo/

Leave a comment