( Tenga en cuenta: hay muchas respuestas para v2, esta es para v3)
Estoy tratando de configurar la label y el title de información sobre herramientas para un gráfico de anillos.
Código:
//Create the donut chart donut = new Chart('questions_positivity_donut', { type: 'doughnut', data: { labels: ["Positive", "Other"], datasets: [{ label: 'Sentiment', data: [user_context.state.avg_joy, (1-user_context.state.avg_joy)], backgroundColor: ['#a9a9a9','#f2f2f2'] }] }, options: { cutout: "70%", plugins: { legend: { display: false }, maintainAspectRatio: false, responsive: true, tooltip: { callbacks: { label: function(context) { let label = new Intl.NumberFormat('en-US', {style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 0}).format(context.formattedValue); return label; }, title: function(context) { let title = context.parsed.x; return title; } }, displayColors: false } } } }); La label ahora funciona y muestra el valor de los datos, pero el title vuelve en blanco, en lugar de devolver la etiqueta de los datos ("Positivo" u "Otro").
¿Cómo puedo devolver el título correcto en tooltip.callback ?
Ejemplo: "Positivo 35%" y "Otro 65%"
Si registra el contexto, podría ver que es una matriz que contiene objetos, con el modo de interacción predeterminado que está utilizando, solo contiene un solo elemento, por lo que puede seleccionarlo y luego acceder al atributo de label de la siguiente manera:
var options = { type: 'doughnut', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"] }] }, options: { plugins: { tooltip: { callbacks: { label: function(context) { let label = new Intl.NumberFormat('en-US', { style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(context.formattedValue); return label; }, title: function(context) { let title = context[0].label; return title; } }, } } } } var ctx = document.getElementById('chartJSContainer').getContext('2d'); new Chart(ctx, options); <body> <canvas id="chartJSContainer" width="600" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script> </body>