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

Chart.js如何为无数据的标签显示Tooltip?

解决Chart.js无数据项无法触发Tooltip的问题

问题场景

使用Chart.js搭配自定义Tooltip时,labels包含12个日期,datasets的data数组最后一项为undefined。hover最后一个标签时,Tooltip的dataIndex无变化,无法显示“暂无数据”提示。现有核心配置如下:

interaction: {
  intersect: false,
  mode: 'index',
},
plugins: {
  tooltip: {
    enabled: false,
    external: onShowTooltip,
    position: 'average',
  },
  // 其他插件配置...
}

解决方案

Chart.js默认会忽略undefined/null类型的数据点,不会为其生成可交互元素,导致hover时无法触发对应索引的Tooltip。通过以下步骤修复:

1. 调整数据与数据集配置

  • 将数据中的undefined替换为null(Chart.js对null的处理更友好,会保留该索引的位置)
  • 为数据集添加配置,保留hover交互区域但隐藏无数据的点:
datasets: [{
  data: [0.22, 0.22, 0.18, 0.24, 0.16, 0.24, 0.18, 0.26, 0.22, 0.16, 0.26, null],
  pointRadius: ctx => ctx.parsed.y === null ? 0 : 3, // 无数据时隐藏点
  pointHitRadius: 10, // 保留hover触发范围
  // 原有数据集配置...
}]

2. 更新交互配置

显式声明包含不可见元素,确保hover能触发无数据项的交互:

interaction: {
  intersect: false,
  mode: 'index',
  includeInvisible: true // 允许触发不可见点的交互事件
}

3. 适配Tooltip逻辑

若使用默认Tooltip:

添加回调判断数据状态,返回对应提示文本:

plugins: {
  tooltip: {
    callbacks: {
      label: ctx => ctx.parsed.y === null ? '暂无数据' : `${ctx.parsed.y}`
    }
  }
}

若使用自定义外部Tooltip:

在onShowTooltip函数中根据索引判断数据状态,渲染对应内容:

function onShowTooltip(context) {
  const tooltip = context.tooltip;
  const dataIdx = tooltip.dataPoints[0].dataIndex;
  const value = context.chart.data.datasets[0].data[dataIdx];
  
  // 自定义渲染逻辑:value为null/undefined时显示“暂无数据”,否则显示原有内容
  const tooltipEl = document.getElementById('custom-tooltip');
  tooltipEl.textContent = value == null ? '暂无数据' : `${value}`;
  // 定位等其他逻辑...
}

效果验证

调整后,hover最后一个标签时,dataIndex会正确指向对应位置,Tooltip可正常显示“暂无数据”提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:08:28