ChartJS:在饼图的工具提示中显示隐藏数据的百分比

时间:2018-08-28 14:58:56

标签: javascript charts chart.js percentage

我有一个带有多个环的饼图,如下所示: Pie Chart

下面的代码使用隐藏的数据label: "Target"生成上面的图表:

 var data = [{
        labels: ["India", "US", "China", "Canada"],
        data: [55, 60, 75, 50],
        label: "Target",
        hidden: true
    }, {
        labels: ["India", "US", "China", "Canada"],
        data: [30, 32, 38, 45],
        backgroundColor: [
            "#4b77a9",
            "#5f255f",
            "#d21243",
            "#B27200"
        ],
        borderColor: "#fff",
        label: "Achieved"
             }, {
        labels: ["Arrivals", "Departure"],
        data: [8, 13],
        backgroundColor: [
            "#92d400",
            "#bbb"
        ],
        borderColor: "#fff"
    }];

我正在用以下代码显示工具提示:

 tooltips: {
   callbacks: {
   label: function (tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].labels[tooltipItem.index];
var values = data.datasets[tooltipItem.datasetIndex].data;
var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var total = 0;
for (var i in values) {
    total += values[i];
}
var percentage = Math.round((value / total) * 100);
var totally = total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
    return [label + " : " + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ' (' + percentage + '%)', "Total : " + totally];
} else {
    return [label + " : " + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ' (' + percentage + '%)', "Total : " + totally];
    }
}
        }
    }

使用上面的工具提示代码,我可以显示每个值占总饼图总数的百分比。 但是,我想实现两件事:

1)在第一环中,显示目标label: "Target",hidden: true对已实现label: "Achieved"的百分比。工具提示中的百分比值为[印度:54.54%,美国:53.33%,中国:50.66%,加拿大:90%]

2)在第二个环中,也不要显示任何百分比和总计。

这是JSFiddle(https://jsfiddle.net/kingBethal/9hj024wy/7/

0 个答案:

没有答案