55SK55
55SK55

Reputation: 691

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
                }]
            }
        }
    });

Upvotes: 3

Views: 16164

Answers (1)

Kunal Khivensara
Kunal Khivensara

Reputation: 1669

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%) ';
        }
      }
    }
  }
});

Upvotes: 7

Related Questions