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

如何在Google Charts API中设置mm:ss格式v轴的最值及刻度

解决Google Charts v轴时长范围设置报错问题

问题原因

你的v轴数据是字符串类型(mm:ss格式),但viewWindow设置了数字秒数,导致数据类型不匹配。Google Charts会尝试对时间类型数据调用getTime方法,但实际数据是字符串,因此抛出a.getTime is not a function错误。

解决方案

将字符串格式的时长转换为Google Charts支持的timeofday类型(格式为[小时, 分钟, 秒, 毫秒]),同时将viewWindow的min/max值改为对应格式的数组,确保类型一致。

修改后的完整代码

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  // load google charts
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);

function drawChart() {
// initialize query statement
var queryUri = 'https://docs.google.com/spreadsheets/d/1xRV24c1itTkK1OWLo3KdpVhkjXpuMzi8lXi4UFHanso/gviz/tq?sheet=Sheet1&headers=1&tq=';

// add select statement, set B as last column
var queryString = encodeURIComponent('SELECT A,D,B');

// initialize query
var query = new google.visualization.Query(queryUri + queryString);

// run query
query.send(function (response) {
// determine if error occurred
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
}

// extract data from response
var data = response.getDataTable();

// need to create dataview to use column as annotation and convert time string to timeofday
var view = new google.visualization.DataView(data);
view.setColumns([
  0,
  {
    calc: function(dataTable, rowIndex) {
      // 提取mm:ss字符串并转换为timeofday格式
      var timeStr = dataTable.getValue(rowIndex, 1);
      var [minutes, seconds] = timeStr.split(':').map(Number);
      return [0, minutes, seconds, 0];
    },
    type: 'timeofday',
    label: data.getColumnLabel(1)
  },
  {
    calc: 'stringify',
    sourceColumn: 2,
    type: 'string',
    role: 'annotation'
  }
]);

// create options
var options = {
  title: 'L\'s 2024 Cross Country Run Times',
  width: 900,
  height: 500,
  trendlines: {
    0: {
      color: 'blue'
    }
  },
  vAxis: {
    format: 'mm:ss',
    viewWindow : {
      min: [0, 11, 0, 0], // 对应11:00
      max: [0, 14, 0, 0]  // 对应14:00
    }
  }
};

// draw chart
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(view, options);
});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
</body>
</html>

关键修改点

  • 在DataView中添加了calc函数,将mm:ss字符串转换为timeofday类型的数组,确保数据类型符合Google Charts的时间格式要求。
  • 将vAxis.viewWindow的min和max值改为timeofday格式的数组,与转换后的数据类型匹配,避免类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:05:25