[Chartjs]-Chart.js Bar graph with percentage values

27👍

You could do something like this:

If you know the absolute value that represents 100% in your dataset, you can pass this to your options object:

    scales: {
  yAxes: [
    {
      ticks: {
        min: 0,
        max: this.max,// Your absolute max value
        callback: function (value) {
          return (value / this.max * 100).toFixed(0) + '%'; // convert it to percentage
        },
      },
      scaleLabel: {
        display: true,
        labelString: 'Percentage',
      },
    },
  ],
},

16👍

With Chart.js 3 you can do this:

const options = {
    scales: {
        y: {
            ticks: {
                format: {
                    style: 'percent'
                }
            }
        }
    }
};

6👍

If you have a static total…say a max value of 800, you can just show custom ticks like this:

ticks: {
    //.. Other settings
    stepSize: 200, /* total/4 shows 0, 25%, 50%, 75%, 100% */             
    callback: function(value, index, values) {
        return ((value / 800) * 100) + '%';
    }
}

5👍

Don’t think there is a out of the box version of that yet.
You might have to do it a bit manually by calculating the percentages before setting the chart up and e.g. follow this example to create the graph:
https://stackoverflow.com/a/40438511/6638478

3👍

I used these options to add percentage to yAxes:

const options = {
  showLines: true,
  scales: {
    yAxes: [
        {
          ticks: {
            min: 0,
            max: 100,
            stepSize: 20,
            callback: function (value) {
              return (value / this.max * 100).toFixed(0) + '%'; // convert it to percentage
              },
          },
          type: "linear",
          display: true,
          position: "left",
          id: "y-axis-1",
          gridLines: {
            drawOnArea: false,
          },
        },
    ],
  },
};

2👍

Of using the toLocaleString function

scales: {
  yAxes: [
    {
      ticks: {
        callback: function (value) {
          return value.toLocaleString('de-DE', {style:'percent'});
        },
      }
    },
  ],
},

Leave a comment