Chart.js 4.4.2:悬停数据点时如何在提示框显示多数据/标签
在Chart.js饼图提示框中添加自定义额外数据
你的核心思路是对的——在数据集里存储自定义的额外字段,再通过提示框回调函数读取这些字段。问题出在Chart.js版本适配上:v3及以上版本中,提示框的配置结构发生了变化,原options.tooltips已被移至options.plugins.tooltip,且回调函数的参数也有调整。
以下是修正后的完整代码:
JavaScript 代码
var ctx = document.getElementById('myChart').getContext('2d'); var data = { title: "2023年8月1日至2024年3月29日的预订时长分布", labels: ["0 - 6天", "7 - 13天", "14 - 20天", "21 - 27天", "28 - 34天"], datasets: [{ data: [2126, 430, 51, 20, 44], backgroundColor: ["#82B6EB", "#434348", "#94EE7E", "#F3A15E", "#8385E8"], // 整合自定义额外数据,结构更清晰 customData: [ { percentage: "79.6 %", bookings: "(2126次预订)" }, { percentage: "16.1 %", bookings: "(430次预订)" }, { percentage: "1.91 %", bookings: "(51次预订)" }, { percentage: "0.75 %", bookings: "(20次预订)" }, { percentage: "1.65 %", bookings: "(44次预订)" } ], hoverOffset: 20 }] }; var myChart = new Chart(ctx, { type: 'pie', data: data, options: { plugins: { tooltip: { // 自定义提示框标题 title: function(context) { return data.title; }, // 自定义提示框内容 callbacks: { label: function(context) { const label = context.label || ''; const value = context.parsed; const customItem = context.dataset.customData[context.dataIndex]; return `${label}: ${value} ${customItem.percentage} ${customItem.bookings}`; } } } } } });
HTML 代码
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script> <div id="_Chart"> <canvas id="myChart" style="width:1700px; max-height: 550px;"></canvas> </div>
关键修正说明:
- 配置位置调整:Chart.js v3+采用插件化配置,提示框设置从
options.tooltips迁移到options.plugins.tooltip。 - 回调参数适配:v3+版本中
label回调接收context对象,需通过context.dataIndex定位当前数据点,context.dataset获取数据集内容。 - 数据结构优化:将分散的
datalabels和databooking合并为customData数组,便于后续维护和扩展。
修改后,鼠标悬停饼图扇区时,提示框会完整显示标签、数值、占比及预订次数信息。
内容的提问来源于stack exchange,提问作者modzking4
相关产品推荐
相关产品推荐

