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
- In Chart.js v3, the
titlecallback receives an array ofTooltipItemobjects. For doughnut charts, each item in this array has alabelproperty that directly maps to yourlabelsarray ("Positive" or "Other"). - 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
相关产品推荐
相关产品推荐

