I need to add the percentage value to the caption (Chartsjs)

Asked

Viewed 39 times

-1

I wanted to add the value of percentages to the caption, I have tried several ways, and still could not the solution to my problem.

Component with chart settings

@Input() chartData: chartData;
@Input() chartLabels: any;

chartOptions = {
    responsive: true,
    cutoutPercentage: 70,
    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 dataset.data[tooltipItem.index] + ' - ' + percentage + "%";
            }
        },
        enabled: true,
    },
    labels: true,
    legend: {
        position: 'right'
    },
};

Component calling the graph

chartPieData = [
    {
        data: [40, 60, 200], 
        backgroundColor: ["rgb(180, 180, 180)", "rgb(127, 129, 132)", "rgb(60, 60, 60)"], 
        borderColor: "rgba(255, 255, 255)",
        label: ['Title1', 'Title2', 'Title3']
    }
];
chartPieLabels = ['Legend1', 'Legend2', 'Legend3'];

inserir a descrição da imagem aqui

1 answer

0

Fixed by editing the Input of the obtained value.

@Input()
set chartLabels(value) {
    this.labels = value;

    const data = this.chartData[0].data;
    const total = this.getTotal(data);

    let index = 0;
    this.labels = this.labels.map(arr => {
        const porcent = Math.floor(((data[index] / total) * 100) + 0.5);
        index++;
        return `${arr} - ${data[index - 1]} - ${porcent}%`;
    });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.