本文介绍了ChartJS:数据标签:在饼图中显示百分比值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有四个标签的饼图:

I have a piechart with four labels:

var data = [{
    data: [50, 55, 60, 33],
    labels: ["India", "China", "US", "Canada"],
    backgroundColor: [
        "#4b77a9",
        "#5f255f",
        "#d21243",
        "#B27200"
    ],
    borderColor: "#fff"
}];

使用 chartjs-plugin-datalabels 插件我想用下面的代码在每个 Pie 块中显示百分比值:

Using chartjs-plugin-datalabels plugin I wanted to show percentage value in each Pie piece with below code:

formatter: (value, ctx) => {

        let datasets = ctx.chart.data.datasets;

        if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
            let sum = 0;
            datasets.map(dataset => {
                sum += dataset.data[ctx.dataIndex];
            });
            let percentage = Math.round((value / sum) * 100) + '%';
            return percentage;
        } else {
            return percentage;
        }
    },
    color: '#fff',
}

我得到了所有馅饼的 100% 价值,而不是各自的百分比.这是 JSFiddle (https://jsfiddle.net/kingBethal/a1Lvn4eb/7/)

I am getting 100% value for all the pie pieces, instead of respective percentages.Here is the JSFiddle (https://jsfiddle.net/kingBethal/a1Lvn4eb/7/)

推荐答案

更新了 2 位小数精度的小提琴.

Updated fiddle with 2 decimal precision.

您没有计算总和,而是仅将当前值存储在每个值的总和中.

You were not computing the sum, instead storing the current value in sum only for every value.

这是工作小提琴:https://jsfiddle.net/a1Lvn4eb/55/

var data = [{
    data: [50, 55, 60, 33],
    labels: ["India", "China", "US", "Canada"],
    backgroundColor: [
        "#4b77a9",
        "#5f255f",
        "#d21243",
        "#B27200"
    ],
    borderColor: "#fff"
}];

var options = {
    tooltips: {
        enabled: false
    },
    plugins: {
        datalabels: {
            formatter: (value, ctx) => {
                let sum = 0;
                let dataArr = ctx.chart.data.datasets[0].data;
                dataArr.map(data => {
                    sum += data;
                });
                let percentage = (value*100 / sum).toFixed(2)+"%";
                return percentage;
            },
            color: '#fff',
        }
    }
};

var ctx = document.getElementById("pie-chart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        datasets: data
    },
    options: options
});

这篇关于ChartJS:数据标签:在饼图中显示百分比值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:32
查看更多