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

Google Charts hAxis重复显示月份 可否用ticks实现仅展示单次月份标签

问题原因

当前你的横轴数据源为字符串类型的离散值,Google Charts默认会为每一行数据对应的横轴值生成标签,因此同一月份存在多条数据时就会重复出现月份标签。使用月份名称作为ticks的取值完全可行,没有强制要求必须使用数字或年份。

解决方案

有两种常用实现方式,可根据你的数据场景选择:

方式1:手动指定ticks

适合数据量小、月份范围固定的场景,直接在hAxis配置中添加ticks参数,传入需要显示的不重复月份列表即可,修改后的完整代码如下:

google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
        ['Month', '2012', '2013', '2014'],
        ['JAN', 3991, 3910, 3820],
        ['JAN', 4316, 4335, 4104],
        ['JAN', 4478, 4439, 4284],
        ['JAN', 4518, 4385, 4213],
        ['FEB', 4496, 4422, 4291],
        ['FEB', 4525, 4503, 4311],
        ['FEB', 4486, 4433, 4323],
        ['FEB', 4441, 4449, 4304],
        ['MAR', 4470, 4383, 4296],
        ['MAR', 4453, 4463, 4413],
        ['MAR', 4462, 4499, 4342],
        ['MAR', 4353, 4491, 4278],
        ['MAR', 4435, 3912, 4154],
        // more data....
    ]);


  var options = {
      legend: {
          position: 'bottom'
      },
      hAxis: {
          textStyle: {
              color: 'red',
          },
          // 新增ticks配置,仅保留需要显示的月份
          ticks: ['JAN', 'FEB', 'MAR']
          // 后续有其他月份直接追加到数组即可
      },
  };

  var chart = new google.visualization.LineChart(document.getElementById('chart'));
  chart.draw(data, options);
}

方式2:自动生成去重ticks

适合数据量大、月份范围不固定的场景,不需要手动维护月份列表,直接从现有数据源中自动提取不重复的月份作为ticks:

google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
        ['Month', '2012', '2013', '2014'],
        ['JAN', 3991, 3910, 3820],
        ['JAN', 4316, 4335, 4104],
        ['JAN', 4478, 4439, 4284],
        ['JAN', 4518, 4385, 4213],
        ['FEB', 4496, 4422, 4291],
        ['FEB', 4525, 4503, 4311],
        ['FEB', 4486, 4433, 4323],
        ['FEB', 4441, 4449, 4304],
        ['MAR', 4470, 4383, 4296],
        ['MAR', 4453, 4463, 4413],
        ['MAR', 4462, 4499, 4342],
        ['MAR', 4353, 4491, 4278],
        ['MAR', 4435, 3912, 4154],
        // more data....
    ]);

  // 自动提取不重复的月份生成ticks
  let monthTicks = [];
  let existMonths = new Set();
  for (let i = 0; i < data.getNumberOfRows(); i++) {
    const currentMonth = data.getValue(i, 0);
    if (!existMonths.has(currentMonth)) {
      existMonths.add(currentMonth);
      monthTicks.push(currentMonth);
    }
  }

  var options = {
      legend: {
          position: 'bottom'
      },
      hAxis: {
          textStyle: {
              color: 'red',
          },
          ticks: monthTicks
      },
  };

  var chart = new google.visualization.LineChart(document.getElementById('chart'));
  chart.draw(data, options);
}

修改完成后重新运行即可实现每个月份仅显示一次标签的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:15:07