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

如何在React Google Charts的柱状图上方显示数值?

在React Google Charts柱状图的柱子上方显示固定数值

要实现柱子上方固定显示数值,需要从数据集配置和图表选项配置两方面入手,具体操作如下:

1. 修改数据集,添加注释列

在你的barChartdata中新增一个标注列,通过{ role: 'annotation' }指定该列的作用是显示注释文本,示例如下:

const barChartdata = [
  ['类别', '数值', { role: 'annotation' }], // 新增注释角色列
  ['产品A', 45, '45'], // 第三个元素就是要显示在柱子上方的内容
  ['产品B', 62, '62'],
  ['产品C', 38, '38'],
  ['产品D', 75, '75']
];

2. 配置图表选项,启用注释显示

在barChartOptions中添加annotations相关配置,控制注释的显示位置、样式:

const barChartOptions = {
  // 你原有配置(如宽高、标题等)
  width: '100%',
  height: '400px',
  
  // 新增注释配置
  annotations: {
    alwaysOutside: true, // 强制注释显示在柱子外侧(上方)
    textStyle: {
      fontSize: 12,
      color: '#333', // 注释文本颜色
      auraColor: 'none' // 去掉注释文本的默认阴影背景
    },
    stem: {
      length: 0 // 去掉注释与柱子之间的连接线
    }
  },
  // 指定要启用注释的系列(单系列写0即可)
  series: {
    0: { annotations: { visible: true } }
  }
};

完整组件示例

import Chart from 'react-google-charts';

const ProductSalesChart = () => {
  const barChartdata = [
    ['产品', '销量', { role: 'annotation' }],
    ['产品A', 45, '45'],
    ['产品B', 62, '62'],
    ['产品C', 38, '38'],
    ['产品D', 75, '75']
  ];

  const barChartOptions = {
    width: '100%',
    height: '400px',
    title: '产品月度销量统计',
    hAxis: { title: '销量' },
    vAxis: { title: '产品' },
    annotations: {
      alwaysOutside: true,
      textStyle: {
        fontSize: 12,
        color: '#222',
        auraColor: 'none'
      },
      stem: {
        length: 0
      }
    },
    series: {
      0: { annotations: { visible: true } }
    }
  };

  return (
    <Chart
      chartType="Bar"
      data={barChartdata}
      options={barChartOptions}
      width={'100%'}
      height={'400px'}
    />
  );
};

export default ProductSalesChart;

关键说明

  • 注释列的内容可以自定义,不一定和数值完全一致,比如可以添加单位(如'45件')
  • 如果是多系列柱状图,需要在series中为每个系列单独配置annotations.visible: true
  • alwaysOutside参数确保注释不会被柱子遮挡,适合柱状图场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:32:14