example chart always javascript chart.js chart.js2

javascript - always - chart js tooltip example



Chart.js 2.0 donut tooltip porcentajes (2)

He trabajado con chart.js 1.0 y tuve la información sobre herramientas de gráficos de anillos mostrando porcentajes basados ​​en datos divididos por conjuntos de datos, pero no puedo replicar esto con el cuadro 2.0.

He buscado alto y bajo y no he encontrado una solución de trabajo. Sé que irá bajo las opciones, pero todo lo que he probado ha hecho que la tarta sea disfuncional en el mejor de los casos.

<html> <head> <title>Doughnut Chart</title> <script src="../dist/Chart.bundle.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <style> canvas { -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } </style> </head> <body> <div id="canvas-holder" style="width:75%"> <canvas id="chart-area" /> </div> <script> var randomScalingFactor = function() { return Math.round(Math.random() * 100); }; var randomColorFactor = function() { return Math.round(Math.random() * 255); }; var randomColor = function(opacity) { return ''rgba('' + randomColorFactor() + '','' + randomColorFactor() + '','' + randomColorFactor() + '','' + (opacity || ''.3'') + '')''; }; var config = { type: ''doughnut'', data: { datasets: [{ data: [ 486.5, 501.5, 139.3, 162, 263.7, ], backgroundColor: [ "#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360", ], label: ''Expenditures'' }], labels: [ "Hospitals: $486.5 billion", "Physicians & Professional Services: $501.5 billion", "Long Term Care: $139.3 billion", "Prescription Drugs: $162 billion", "Other Expenditures: $263.7 billion" ] }, options: { responsive: true, legend: { position: ''bottom'', }, title: { display: false, text: ''Chart.js Doughnut Chart'' }, animation: { animateScale: true, animateRotate: true } } }; window.onload = function() { var ctx = document.getElementById("chart-area").getContext("2d"); window.myDoughnut = new Chart(ctx, config);{ } }; </script> </body> </html>


Para aquellos que desean mostrar porcentajes dinámicos basados ​​en lo que se muestra actualmente en el gráfico (no basado en datos totales), puede probar este código:

tooltips: { callbacks: { label: function(tooltipItem, data) { var dataset = data.datasets[tooltipItem.datasetIndex]; var meta = dataset._meta[Object.keys(dataset._meta)[0]]; var total = meta.total; var currentValue = dataset.data[tooltipItem.index]; var percentage = parseFloat((currentValue/total*100).toFixed(1)); return currentValue + '' ('' + percentage + ''%)''; }, title: function(tooltipItem, data) { return data.labels[tooltipItem[0].index]; } } },


Actualización: la respuesta a continuación muestra un porcentaje basado en los datos totales, pero @William Surya Permana tiene una excelente respuesta que se actualiza según los datos mostrados https://.com/a/49717859/2737978

En las options puede pasar un objeto de información sobre tooltips (puede leer más en los documentos de chartjs )

Un campo de información sobre tooltips , para obtener el resultado que desea, es un objeto de callbacks con un campo de label . label será una función que incluye el elemento de información sobre herramientas sobre el que se ha desplazado y los datos que componen su gráfico. Simplemente devuelva una cadena, que desea ir en la información sobre herramientas, desde esta función.

Aquí hay un ejemplo de cómo puede verse esto.

tooltips: { callbacks: { label: function(tooltipItem, data) { //get the concerned dataset var dataset = data.datasets[tooltipItem.datasetIndex]; //calculate the total of this data set var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) { return previousValue + currentValue; }); //get the current items value var currentValue = dataset.data[tooltipItem.index]; //calculate the precentage based on the total and current item, also this does a rough rounding to give a whole number var percentage = Math.floor(((currentValue/total) * 100)+0.5); return percentage + "%"; } } }

y un ejemplo completo con los datos que proporcionó

fiddle

var randomScalingFactor = function() { return Math.round(Math.random() * 100); }; var randomColorFactor = function() { return Math.round(Math.random() * 255); }; var randomColor = function(opacity) { return ''rgba('' + randomColorFactor() + '','' + randomColorFactor() + '','' + randomColorFactor() + '','' + (opacity || ''.3'') + '')''; }; var config = { type: ''doughnut'', data: { datasets: [{ data: [ 486.5, 501.5, 139.3, 162, 263.7, ], backgroundColor: [ "#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360", ], label: ''Expenditures'' }], labels: [ "Hospitals: $486.5 billion", "Physicians & Professional Services: $501.5 billion", "Long Term Care: $139.3 billion", "Prescription Drugs: $162 billion", "Other Expenditures: $263.7 billion" ] }, options: { responsive: true, legend: { position: ''bottom'', }, title: { display: false, text: ''Chart.js Doughnut Chart'' }, animation: { animateScale: true, animateRotate: true }, 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 + "%"; } } } } }; var ctx = document.getElementById("chart-area").getContext("2d"); window.myDoughnut = new Chart(ctx, config); { }

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.bundle.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="canvas-holder" style="width:75%"> <canvas id="chart-area" /> </div>