Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom text to Bar Chart label values using Chart.js

I'm using Chart.js plugin to show a Bar Chart and I'm getting output as below:

enter image description here My question is about, how to add a custom text after rendering a value to bar? For example, In Jan, value is showing 56. I want to add % increased/decreased information next to it (i.e. 56 [115 %]) How to do this?

Here's my code

    window.chartHeadcount = new Chart(document.getElementById("barChartHeadcount"), {
        type: 'bar',
        data: {
            labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            datasets: [{
                label: 'Billed',
                backgroundColor: 'rgb(0, 197, 106)',
                data: billedHeadCount
            }, {
                label: 'Unbilled',
                backgroundColor: 'rgb(255, 114, 107)',
                data: unBilledHeadCount
            }]
        },
        options: {
            title: {
                display: true,
                text: 'Community Headcount - ' + Options.Globals.Year
            },
            tooltips: {
                mode: 'index',
                intersect: false
            },
            responsive: true,
            scales: {
                xAxes: [{
                    stacked: false
                }],
                yAxes: [{
                    stacked: false
                }]
            }
        }
    });
like image 394
55SK55 Avatar asked Aug 24 '26 13:08

55SK55


1 Answers

You can use the plugin chartjs-datalabels and set the formatter property to set your custom labels.

Created a fiddle for your reference -> http://jsfiddle.net/upmth2cq/1/

Hope it helps!

new Chart(document.getElementById("barChartHeadcount"), {
  type: 'bar',
  data: {
    labels: ['Jan', 'Feb', 'Mar'],
    datasets: [{
      label: 'Billed',
      backgroundColor: 'rgb(0, 197, 106)',
      data: [56, 63, 67]
    }, {
      label: 'Unbilled',
      backgroundColor: 'rgb(255, 114, 107)',
      data: [1, 2, 3]
    }]
  },
  options: {
    title: {
      display: true,
      text: 'Community Headcount'
    },
    tooltips: {
      mode: 'index',
      intersect: false
    },
    responsive: true,
    scales: {
      xAxes: [{
        stacked: false
      }],
      yAxes: [{
        stacked: false
      }]
    },
    plugins: {
      datalabels: {
        align: 'end',
        anchor: 'end',
        backgroundColor: function(context) {
          return context.dataset.backgroundColor;
        },
        borderRadius: 4,
        color: 'white',
        formatter: function(value){
            return value + ' (100%) ';
        }
      }
    }
  }
});
like image 91
Kunal Khivensara Avatar answered Aug 27 '26 03:08

Kunal Khivensara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!