如何在图表饼中添加“%”(chartjs)

时间:2018-12-05 20:00:38

标签: javascript charts label chart.js

我需要在图表中的数字后加上%:

赞:100%

enter image description here

这是我使用图表js制作图表的代码:

new Chart(document.getElementById("pie-chart-one"), {
    type: 'doughnut',
    data: {
        labels: ['Transmitidas', 'Não Transmitidas'],
        datasets: [{
            data: [@Model.PorcentQtdDeclaracoesStatusTransmitida, @Model.PorcentQtdDeclaracoesStatusNaoTransmitida],
            backgroundColor: backgroudColor,
            borderWidth: 1,
        }]
    },
    options: {
        legend: {
            display: true,
            position: 'bottom',
            fontSize: 10

        },
       responsive:false,
       fontsize: 11,
       layout: {
           padding: {
               left: 0,
               right: 0,
               top: 30,
               bottom: 30
           }
        }
    }
});

2 个答案:

答案 0 :(得分:0)

在选项定义中...

options: {
        tooltips: {
            enabled: true,
            mode: 'single',
            callbacks: {
                label: function(tooltipItems, data) { 
                    return tooltipItems.yLabel + ' %';
                }
            }
        },
 } 

答案 1 :(得分:0)

我使用工具提示中的回调和标题解决了这个问题:

options: {
        tooltips: {
            callbacks: {
                label: function (tooltipItem, data) {
                    var dataset = data.datasets[tooltipItem.datasetIndex];
                    var total = dataset.data.reduce(function (previousValue, currentValue, currentIndex, array) {
                        return previousValue + currentValue;
                    });
                    var currentValue = dataset.data[tooltipItem.index];
                    var percentage = Math.floor(((currentValue / total) * 100) + 0.5);
                    return percentage + "%";
                },                    
                title: function (tooltipItem, data) {
                    return data.labels[tooltipItem[0].index];
                }
            }
        }