首页 > 解决方案 > Highchart DateTime Axis:如何将不存在的数据显示为 0 或间隙

问题描述

我有一个日期时间模式的图表,我给它一个包含 7 个类别/行的数据,lib 正在生成空类别数据(我没有 2019 年 2 月、2019 年 4 月的数据......)这很好,所以类别轴上的间隔停留一个月。如果我想将缺失数据显示为 0(空数据)怎么办?

我不能只为 2 月和 4 月添加空条目,因为我的数据来自动态数组,我想避免在该数组上循环以查找丢失的数据。我已经设置了一个小提琴来帮助排序

https://jsfiddle.net/3qob5j49/

这是我的 xAxis 设置

"xAxis": {
"type": "datetime",
"title": {
    "text": "",
    "align": "middle",
    "style": {
        "fontFamily": "Open Sans",
        "fontSize": "14px",
        "textShadow": "",
        "fontWeight": 400,
        "fontStyle": "italic",
        "textDecoration": "",
        "color": "rgba(62,78,91,0.5)"
    }
},
"categories": null,
"lineColor": "rgba(191,191,191,1)",
"lineWidth": 1,
"gridLineWidth": 0,
"gridLineColor": "rgba(242,242,242,1)",
"gridZIndex": 2,
"minorGridLineWidth": 0,
"minorGridLineColor": "#CCCCCC",
"tickColor": "transparent",
"tickLength": 5,
"crosshair": false,
"tickWidth": 0,
"labels": {
    "enabled": true,
    "rotation": 90,
    "step": null,
    "style": {
        "fontFamily": "Open Sans",
        "fontSize": "14px",
        "textShadow": "",
        "fontWeight": 400,
        "fontStyle": "",
        "textDecoration": "",
        "color": "rgba(127,127,127,1)"
    }
}

您可以查看以下描述我正在尝试执行的操作的图片。

谢谢

标签: javascripthighcharts

解决方案


您可以遍历数据数组以查找过大的时间间隔并在正确的位置插入额外的点:

var dynamicData = [
        [1538344800000, 2],
        [1541026800000, 3],
        [1543618800000, 4],
        [1546297200000, 5],
        [1551394800000, 6],
        [1556661600000, 8],
        [1561932000000, 9]
    ],
    maxInterval = 2682000000,
    i = 0;

for (; i < dynamicData.length - 1; i++) {
    if (dynamicData[i + 1][0] - dynamicData[i][0] > maxInterval) {

        dynamicData.splice(
            i + 1,
            0, [dynamicData[i][0] + (dynamicData[i + 1][0] - dynamicData[i][0]) / 2, 0]
        )
    }
}

现场演示:http: //jsfiddle.net/BlackLabel/nwjL0omv/


推荐阅读