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

Chart.js如何设置静态小时标签并填充动态数据(缺省补0)

Solution: Show Full 24-Hour Labels with 0 for Missing Data

Got it, let's get this sorted for you! The core idea is to first define a complete set of hourly labels covering every hour from 12 AM (00:00) to 11 PM (23:00), then map your fetched API data to these labels—filling in 0 for any hours that don't have corresponding data. Here's how to adjust your code step by step:

Step 1: Generate Full 24-Hour Labels

First, create a helper function to generate all 24 hours in the exact timestamp format your API uses. This ensures our chart always has the full range of hourly labels:

// Helper function to generate complete 24-hour labels (matches your API's timestamp format)
function generateFullHourLabels() {
  const labels = [];
  for (let hour = 0; hour < 24; hour++) {
    // Format hour as two digits (e.g., 0 → 00) to match API timestamp format
    const formattedHour = hour.toString().padStart(2, '0');
    labels.push(`${formattedHour}:00:00.000000`);
  }
  return labels;
}

Step 2: Initialize Chart with Full Labels & Empty Data

Update your chart initialization to use the full 24-hour labels from the start, and set initial data to an array of 24 zeros (so the chart shows empty bars immediately):

// 创建初始空图表
var ctx_live = document.getElementById("chLine");
var myChart = new Chart(ctx_live, {
    type: 'bar',
    data: {
        labels: generateFullHourLabels(), // Use full 24-hour labels upfront
        datasets: [{
            data: Array(24).fill(0), // Initialize with 24 zeros
            borderWidth: 1,
            borderColor:'#00c0ef',
            label: 'liveCount',
        }]
    },
    options: {
        responsive: true,
        title: {
            display: true,
            text: "Count Per Hour",
        },
        legend: { display: false },
        scales: {
            yAxes: [{
                ticks: { beginAtZero: true, }
            }]
        }
    }
});

Step 3: Modify Data Fetch Logic to Map to Full Labels

Adjust your getData function to convert the fetched data into a key-value map (for quick lookups), then iterate over the full 24-hour labels to fill in data or 0 where missing:

// 获取新数据逻辑
var getData = function() {
    const fullLabels = generateFullHourLabels();
    const fullData = [];
    // Create a map to store fetched data by timestamp for fast lookup
    const dataMap = {};

    $.ajax({
        url: 'chart_data',
        type: "get",
        success: function(data) {
            const fetchedData = JSON.parse(data);
            // Populate the map: key = timestamp, value = true_count
            fetchedData.forEach(item => {
                dataMap[item.timestamp] = item.true_count;
            });

            // Match each full label to the map—use 0 if no data exists for the hour
            fullLabels.forEach(label => {
                fullData.push(dataMap[label] || 0);
            });

            // Update the chart with the complete dataset
            myChart.data.datasets[0].data = fullData;
            myChart.update();
        }
    });
};

Step 4: Keep the Interval for Auto-Refresh

Your existing interval code works fine—keep it to refresh the data every 3 seconds:

// 每3秒获取一次新数据
setInterval(getData, 3000);

Key Notes:

  • We use a dataMap to avoid looping through the fetched data 24 times (this is more efficient, especially if your dataset grows).
  • The padStart(2, '0') ensures hours like 9 are formatted as 09 to match your API's timestamp format (e.g., 09:00:00.000000 instead of 9:00:00.000000).
  • By initializing the chart with full labels and zero data, users see the complete 24-hour range immediately, even before the first API call finishes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 06:17:43