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

React Google Charts堆叠柱状图:如何在柱状条上显示注释

在堆叠柱状图的柱状条上显示注释的实现方法

我尝试在堆叠柱状图的柱状条上显示注释,但找不到相关示例。查阅Google Charts文档并结合React示例后,仍不清楚具体实现方式,推测这和column roles有关。

解决方案

要实现堆叠柱状图的柱状条注释,确实需要用到Google Charts的column roles中的annotation类型,具体实现步骤如下:

  1. 调整数据结构:在每个数值列后添加对应的注释列,通过{ role: "annotation" }标记列角色
  2. 配置图表选项:开启注释显示并自定义样式

修改后的完整代码

import React from "react";
import { Chart } from "react-google-charts";

// 为每个数值列配置对应的注释列
export const data = [
  ["", "Density", { role: "annotation" }, "Copper", { role: "annotation" }, "Silver", { role: "annotation" }, "Gold", { role: "annotation" }],
  ["", 8, "8", 10, "10", 19, "19", 21, "21"],
];

const barChartOptions = {
  title: 'Medals',
  isStacked: 'percent',
  chartArea: { left: 25, top: 65, bottom: 30, right: 220 },
  hAxis: {
    textPosition: 'none', 
    gridlines: { color: 'transparent' }
  },
  vAxis: {
    textPosition: 'none', 
    gridlines: { color: 'transparent' }
  },
  // 配置注释显示样式
  annotations: {
    alwaysOutside: false, // 让注释显示在柱状条内部
    textStyle: {
      fontSize: 12,
      color: '#fff',
      bold: true
    }
  }
};

export function App() {
  return (
    <Chart 
      chartType="ColumnChart" 
      width="100%" 
      height="400px" 
      data={data} 
      options={barChartOptions}
    />
  );
}

关键说明

  • 数据数组中,每个数值列(如"Density")后必须紧跟一个标记为annotation的列,对应数据行填入要显示的注释文本
  • 设置annotations.alwaysOutside: false可让注释嵌入柱状条内部,避免堆叠布局下注释溢出
  • 通过annotations.textStyle可自定义注释的字体大小、颜色、粗细等样式

参考示例(非堆叠柱状图标签效果)

非堆叠柱状图标签示例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:50:38