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

Chart.js柱状图悬停提示框(Tooltip)不显示问题

柱状图悬停提示不显示问题

我希望在柱状图上悬停时显示numberValue的数值作为提示标签,但尝试多种实现方式后,悬停柱状图时仍无提示内容出现。相关代码如下:

getBarChart() {
    this.http.get(API).subscribe({
      next: (data) => {
        this.totalAmount= data;
        let splitted = this.totalAmount.toString().split(",");
        let numberValue= splitted[0];
        let totalAmountPerMonth = splitted[1];
        let month = splitted[2];

        this.barChart.data.labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

        let dataValues = new Array(12).fill(null);
        let monthIndex = parseInt(month) - 1;
        dataValues[monthIndex] = totalAmountPerMonth;

        this.barChart.data.datasets = [
          {
            label: "Total Amount",
            data: dataValues,
            backgroundColor: DARK_BLUE
          }
        ];
        this.barChart.update();
      },
      error: (err) => {
        console.log(err);
      }
    });

    Chart.register(BarController);
    Chart.register(CategoryScale);
    Chart.register(LinearScale);
    Chart.register(BarElement);

    this.barChart = new Chart("barChart", {
      type: 'bar',
      data: {
        labels: [],
        datasets: []
      },
      options: {
        aspectRatio: 2.5,
        scales: {
          x: {
            title: {
              display: true,
              text: "Month"
            }
          },
          y: {
            title: {
              display: true,
              text: "Total Amount"
            }
          }
        },
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: (context) => {
                const value = context.dataset.data[context.dataIndex];
                const numberValue = value !== null ? value : 'N/A';
                return `Number: ${numberValue}`;
              }
            }
          }
        },
      }
    });
  }

问题原因分析

  1. 未注册Tooltip插件:代码仅注册了Bar相关控制器和刻度组件,未注册Tooltip插件,导致Chart.js的tooltip功能未启用。
  2. 变量作用域冲突:API回调内定义的numberValue是局部变量,tooltip回调无法访问该变量;当前回调里的numberValue只是对数据值的重命名,并非目标值。
  3. 空值默认行为:数据数组中多数元素为null,Chart.js默认不会为null值的柱子触发tooltip。

解决方法

1. 注册Tooltip插件

在Chart组件注册代码中添加Tooltip插件:

Chart.register(BarController);
Chart.register(CategoryScale);
Chart.register(LinearScale);
Chart.register(BarElement);
Chart.register(Tooltip); // 新增注册Tooltip

2. 存储目标numberValue到组件属性

在组件类中定义属性存储numberValue,让tooltip回调可访问:

// 组件类内新增属性
private chartNumberValue: string;

// 在API订阅的next回调中赋值
this.chartNumberValue = splitted[0];

3. 修正Tooltip回调逻辑

直接使用组件存储的目标值,同时处理空值情况:

tooltip: {
  callbacks: {
    label: (context) => {
      const value = context.dataset.data[context.dataIndex];
      // 仅当数据存在时显示提示
      if (value !== null) {
        return `Number: ${this.chartNumberValue}`;
      }
      return '';
    }
  }
}

4. 统一数据类型

将totalAmountPerMonth转换为数字类型,避免Chart.js解析异常:

dataValues[monthIndex] = Number(totalAmountPerMonth);

修改后的完整代码

// 组件类新增属性
private chartNumberValue: string;

getBarChart() {
    this.http.get(API).subscribe({
      next: (data) => {
        this.totalAmount= data;
        let splitted = this.totalAmount.toString().split(",");
        // 存储目标numberValue
        this.chartNumberValue = splitted[0];
        let totalAmountPerMonth = splitted[1];
        let month = splitted[2];

        this.barChart.data.labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

        let dataValues = new Array(12).fill(null);
        let monthIndex = parseInt(month) - 1;
        // 转换为数字类型
        dataValues[monthIndex] = Number(totalAmountPerMonth);

        this.barChart.data.datasets = [
          {
            label: "Total Amount",
            data: dataValues,
            backgroundColor: DARK_BLUE
          }
        ];
        this.barChart.update();
      },
      error: (err) => {
        console.log(err);
      }
    });

    // 注册所有必要组件
    Chart.register(BarController);
    Chart.register(CategoryScale);
    Chart.register(LinearScale);
    Chart.register(BarElement);
    Chart.register(Tooltip);

    this.barChart = new Chart("barChart", {
      type: 'bar',
      data: {
        labels: [],
        datasets: []
      },
      options: {
        aspectRatio: 2.5,
        scales: {
          x: {
            title: {
              display: true,
              text: "Month"
            }
          },
          y: {
            title: {
              display: true,
              text: "Total Amount"
            }
          }
        },
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: (context) => {
                const value = context.dataset.data[context.dataIndex];
                if (value !== null) {
                  return `Number: ${this.chartNumberValue}`;
                }
                return '';
              }
            }
          }
        },
      }
    });
  }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:28:09