Quiero mostrar la distribución porcentual en un gráfico circular. Mi gráfico actual es perfecto, excepto que no tiene etiquetas de porcentaje. Cómo sumar porcentaje. mi código parece;
<!DOCTYPE html> <html> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <body> <canvas id="myChart" style="width:100%;max-width:600px"></canvas> <script> var xValues = ["Italy", "France", "Spain", "USA", "Argentina"]; var yValues = [55, 49, 44, 24, 15]; var barColors = [ "#b91d47", "#00aba9", "#2b5797", "#e8c3b9", "#1e7145" ]; new Chart("myChart", { type: "pie", data: { labels: xValues, datasets: [{ backgroundColor: barColors, data: yValues }] }, options: { title: { display: true, text: "World Wide Car Production" } } }); </script> </body> </html>Solo necesita importar algo de <script> de chart js. y luego simplemente modifique un poco su código como se muestra a continuación;
<!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script> </head> <body> <canvas id="myChart" style="width:100%;max-width:600px"></canvas> <script> var xValues = ["Italy", "France", "Spain", "USA", "Argentina"]; var yValues = [55, 49, 44, 24, 15]; var barColors = [ "#b91d47", "#00aba9", "#2b5797", "#e8c3b9", "#1e7145" ]; var ctx = document.getElementById("myChart").getContext('2d'); var myChart =new Chart(ctx, { type: "pie", data: { labels: xValues, datasets: [{ backgroundColor: barColors, data: yValues }] }, options:{ tooltips: { enabled: true }, plugins: { datalabels: { formatter: (value, ctx) => { let sum = ctx.dataset._meta[0].total; let percentage = (value * 100 / sum).toFixed(2) + "%"; return percentage; }, color: '#fff', } }, title: { display: true, text: "World Wide Car Production" } } }); </script> </body> </html>