[Chartjs]-Chart.js – How To Show Value of Label as Percent of X and Y Values – Currently Always 100%

4πŸ‘

βœ…

You can create your own render function like this:

...

render: function (args) {  
  let max = 17; //This is the default 100% that will be used if no Max value is found
  try {
    //Try to get the actual 100% and overwrite the old max value
    max = Object.values(args.dataset.data).map((num) => {
      return +num; //Convert num to integer
    });
    max = Math.max.apply(null, max);
  } catch (e) {}
  return Math.round(args.value * 100 / max);
}

...

Here is the example code: https://jsbin.com/hihexutuyu/1/edit

You can actually erase the try/catch block and define only max value and it will work. It would look like this:

...

render: function (args) {  
  let max = 17; //Custom maximum value

  return Math.round(args.value * 100 / max);
}

...

The try/catch block is only to automatically get the maximum value from the dataset.

The plugin documentation, with all other possible settings that can be added to render is here: https://github.com/emn178/chartjs-plugin-labels.

1πŸ‘

I’m not sure I have a complete grasp of what you’re trying to achieve, but you could use a callback function to generate the desired result along the yAxes, similar to this:

yAxes:[{
    ticks:{
        callback:function(value,index,values){
            return ((value / index) * 100)+'% ';
        }
    }
}]

Leave a comment