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

如何将Google柱状图Tooltip移至鼠标指向柱子正上方

调整Google柱状图Tooltip至柱子正上方的解决方案

问题背景

Google柱状图默认Tooltip显示在柱子右侧,需调整至柱子正上方,此前尝试相关方案导致图表无法加载。

解决方案

通过Google Charts官方支持的tooltip.positioner函数自定义Tooltip位置,结合CSS调整样式,确保定位准确且图表正常加载。

1. 修改JavaScript配置

更新options中的tooltip配置,添加自定义位置计算函数:

var options = {
  title: "Spending - Last 7 days",
  backgroundColor: "#FFFAF5",
  width: width,
  height: height,
  chartArea: { left: "5%", right: "5%", top: "25%", bottom: "10%" },
  bar: { groupWidth: "68%" },
  titleTextStyle: {
    color: "#382314",
    fontName: "DM Sans",
    fontSize: 24,
  },
  tooltip: {
    isHtml: true,
    // 自定义Tooltip位置计算函数
    positioner: function(selection, position) {
      var chartLayout = this.getChartLayoutInterface();
      var barBounds = chartLayout.getBoundingBox('bar#' + selection.row + '#' + selection.column);
      
      // 定位到柱子正上方居中,与柱子保持8px间距
      return {
        left: barBounds.left + barBounds.width / 2 - position.width / 2,
        top: barBounds.top - position.height - 8
      };
    }
  },
  allowHtml: true,
  vAxis: {
    textPosition: "none",
    baselineColor: "none",
    gridlines: { count: 0 },
  },
  hAxis: {
    textStyle: { color: "#93867B", fontName: "DM Sans" },
  },
  legend: { position: "none" },
  colors: [chartColor],
};

2. 调整Tooltip CSS样式

修改CSS,确保Tooltip绝对定位且清除默认偏移:

.google-visualization-tooltip {
  color: white !important;
  background-color: rgb(11, 11, 11) !important;
  font-family: "DM Sans", sans-serif !important;
  border-radius: 18% !important;
  padding: 0.3% !important;
  text-align: center !important;
  border: none !important;
  z-index: 999 !important;
  position: absolute !important;
  transform: none !important; /* 移除默认位移效果,保证自定义定位生效 */
}

说明

  • 采用官方positioner函数属于标准配置,不会引发图表加载失败问题
  • 通过getChartLayoutInterface()获取柱子精确坐标,确保Tooltip始终对齐柱子正上方
  • CSS中清除默认transform避免位置偏移,保证自定义定位逻辑生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:09:52