使用 Chart.js 向条形图标签值添加自定义文本

55S*_*K55 2 jquery label chart.js

我正在使用 Chart.js 插件来显示条形图,并且得到如下输出:

在此处输入图片说明 我的问题是,如何在将值渲染到 bar 后添加自定义文本?例如,在 Jan,值显示 56。我想在它旁边添加 % 增加/减少的信息(即 56 [115 %]) 如何做到这一点?

这是我的代码

    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
                }]
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

Kun*_*ara 6

您可以使用插件 chartjs-datalabels 并设置 formatter 属性来设置您的自定义标签。

创建了一个小提琴供您参考 - > http://jsfiddle.net/upmth2cq/1/

希望能帮助到你!

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%) ';
        }
      }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)