You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chart.js v3.5环形图Tooltip标题回调返回空白问题及配置优化咨询

Fix Tooltip Title for Chart.js v3 Doughnut Chart

Got it, let's sort out why your tooltip title is showing up blank. The problem lies in how you're trying to fetch the label in the title callback—context.parsed.x doesn't exist for doughnut charts (since they’re part of the pie chart family, which uses parsed.y for data values, and labels are stored in a different property).

Here's how to fix this:

Step-by-Step Breakdown

  1. In Chart.js v3, the title callback receives an array of TooltipItem objects. For doughnut charts, each item in this array has a label property that directly maps to your labels array ("Positive" or "Other").
  2. Instead of trying to pull the label from parsed.x, just access it from the first item in the context array.

Modified Working Code

// 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%",
 maintainAspectRatio: false,
 responsive: true, // Moved these two to top-level options (they don't belong in plugins)
 plugins: {
 legend: { display: false },
 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) {
 // Fetch the correct label from the first tooltip item
 return context[0].label;
 }
 },
 displayColors: false
 }
 }
 }
});

Bonus: Single-Line Tooltip (Label + Percentage)

If you want the tooltip to show a single line like "Positive 35%" instead of separate title and label sections, you can simplify by combining both in the label callback and disabling the title:

label: function(context) {
 const categoryLabel = context.label;
 const percentage = new Intl.NumberFormat('en-US', {style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 0}).format(context.formattedValue);
 return `${categoryLabel} ${percentage}`;
},
title: function() { return null; } // Hide the title entirely

内容的提问来源于stack exchange,提问作者Izzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:28:10