Google Charts时间轴:强制显示全部小时而非每2小时显示一次
Solution for Google Charts Timeline Custom Tick & Gridline Requirements
Absolutely feasible! Let's walk through how to force full hour ticks regardless of screen size and add unlabeled 15-minute divider lines to your Timeline chart.
1. Force Full Hour Ticks
Google Charts Timeline auto-scales ticks by default, but we can override this by explicitly defining all hour ticks using hAxis.ticks. First, you'll need to generate an array of Date objects for every hour within your chart's time range.
2. Add 15-Minute Unlabeled Dividers
We'll use hAxis.minorGridlines to create these unlabeled lines. Set the count property to split each hour into 15-minute segments, or use an explicit interval value for clearer control.
Modified Code Example
Here's how to integrate these changes into your existing code:
google.charts.load('current', {'packages':['timeline']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var container = document.getElementById('timeline'); var chart = new google.visualization.Timeline(container); var dataTable = new google.visualization.DataTable(); // Add your data columns and rows (adjust to match your actual data) dataTable.addColumn({ type: 'string', id: 'Task' }); dataTable.addColumn({ type: 'string', id: 'Name' }); dataTable.addColumn({ type: 'date', id: 'Start' }); dataTable.addColumn({ type: 'date', id: 'End' }); dataTable.addRows([ ['Backend Deployment', 'Dev Team', new Date(2024, 4, 1, 9, 0), new Date(2024, 4, 1, 16, 0)], ['UI Testing', 'QA Team', new Date(2024, 4, 1, 10, 30), new Date(2024, 4, 1, 15, 0)] ]); // Define your chart's time range (can be dynamic by iterating data rows) var startTime = new Date(2024, 4, 1, 9, 0); var endTime = new Date(2024, 4, 1, 16, 0); // Generate array of full-hour ticks var hourTicks = []; for (var d = new Date(startTime); d <= endTime; d.setHours(d.getHours() + 1)) { hourTicks.push(new Date(d)); } var options = { timeline: { showRowLabels: true }, hAxis: { // Force all defined hour ticks to display ticks: hourTicks, // Lock time range to prevent auto-scaling viewWindow: { min: startTime, max: endTime }, // Add 15-minute unlabeled gridlines minorGridlines: { count: 3, // 3 lines per hour = 15-minute intervals (60/15 - 1) color: '#e0e0e0' // Optional: soft gray color for subtle dividers } } }; chart.draw(dataTable, options); }
Key Notes
- Dynamic Time Range: If your data's start/end times change, replace the hardcoded
startTime/endTimewith logic that finds the earliest start and latest end from your data rows. - Explicit Interval: Instead of
count: 3, you can useinterval: { value: 15, unit: 'minute' }for more readable control over the 15-minute spacing. - Tick Persistence: The fixed
viewWindowensures the chart doesn't shrink or expand the time range automatically, keeping your custom ticks visible even on small screens.
内容的提问来源于stack exchange,提问作者Rafael Grilli
相关产品推荐
相关产品推荐

