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

ChartJS双X轴数据点索引标签异常问题求助

解决ChartJS双X轴数据集Tooltip标签不显示问题

问题根源分析

  1. 标签拼写不一致:第二个数据集的label为'Ages Invlolved'(缺少字母l),但Tooltip回调中判断的是'Ages Involved',导致条件不触发,无法获取对应X轴标签。
  2. 数据集未绑定目标X轴:第二个数据集未配置xAxisID: 'x2',ChartJS默认将其关联到第一个X轴(x1),数据点索引与x2标签不匹配。
  3. Legend点击事件逻辑错误:判断datasetIndex === 2,但实际仅存在两个数据集(索引0、1),该分支永远不会执行。
  4. X轴类型未明确:自定义分类X轴需指定type: 'category',否则ChartJS无法正确解析标签列表。

修复后的完整代码

const data = {
  datasets: [{
      label: 'Races/Ethnicities Involved', // 修正拼写错误
      data: [109, 1289, 245, 16, 7],
      backgroundColor: 'rgba(255, 26, 104, 0.2)',
      borderColor: 'rgba(255, 26, 104, 1)',
      tension: 0.4,
      yAxisID: 'y',
      xAxisID: 'x1' // 明确绑定x1轴
  }, 
  {
      label: 'Ages Involved', // 修正拼写错误
      data: [161, 746, 534, 202, 23],
      backgroundColor: 'rgba(0, 26, 104, 0.2)',
      borderColor: 'rgba(0, 26, 104, 1)',
      tension: 0.4,
      xAxisID: 'x2' // 绑定x2轴
  }]
};

const config = {
  type: 'line',
  data,
  options: {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      y: {
        beginAtZero: true,
        type: 'linear',
        position: 'left'
      },
      x1: {
        type: 'category', // 明确分类轴类型
        labels: ['White (Non-Hispanic)', 'Black (Non-Hispanic)', 'Hispanic (Black Or White)', 'Asian', 'Unknown'],
      },
      x2: {
        type: 'category', // 明确分类轴类型
        position: 'top',
        labels: ['Younger than 18', '18-30', '31-45', 'Older than 45', 'Unknown'],
      },
    },
    plugins: {
      tooltip: {
        callbacks: {
          title: function(tooltipItems) {
            const datasetIndex = tooltipItems[0].datasetIndex;
            return config.data.datasets[datasetIndex].label;
          },
          label: function(context) {
            const datasetLabel = context.dataset.label; // 直接从context获取,无需再从config取
            const value = context.parsed.y;
            let xLabel;
        
            if (datasetLabel === 'Races/Ethnicities Involved') {
                xLabel = config.options.scales.x1.labels[context.dataIndex];
            } else if (datasetLabel === 'Ages Involved') {
                // 直接从x2轴取标签,无需手动判断索引
                xLabel = config.options.scales.x2.labels[context.dataIndex];
                console.log(context.dataIndex); // 现在会正常打印日志
            }
            return `${xLabel}: ${value}`;
          } 
        }
      }
    }
  }
};

// 初始化图表
const myChart = new Chart(
  document.getElementById('chart'),
  config
);

// 修复Legend点击事件逻辑
myChart.legend.options.onClick = function(event, legendItem) {
  const datasetIndex = legendItem.datasetIndex;
  const dataset = myChart.data.datasets[datasetIndex];
  
  // 针对第二个数据集(索引1)切换标签
  if (datasetIndex === 1) { 
    dataset.label = dataset.label === 'Ages Involved' 
      ? 'Race/Ethnicity Involved' 
      : 'Ages Involved';
    myChart.update();
  }
};

// 显示Chart.js版本
const chartVersion = document.getElementById('chartVersion');
chartVersion.innerText = Chart.version;

关键修复点说明

  • 修正了两个数据集label的拼写错误,确保判断条件匹配。
  • 给每个数据集添加xAxisID,明确绑定对应的X轴。
  • 为X轴添加type: 'category',确保分类标签生效。
  • 简化Tooltip标签获取逻辑,直接从对应X轴的labels数组中取,无需手动分支判断。
  • 修复Legend点击事件的数据集索引判断,针对实际存在的索引(1)处理标签切换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:43:23