dygraphs标签数量与数组中列数不匹配

时间:2016-10-04 11:09:28

标签: javascript arrays dygraphs

无法让dygraph工作。

我有一个从PHP填充的数组,如下所示:

data = [
{
    "DATA": "2016-01-22",
    "TOTAL": [
        "7",
        "4",
        "20",
        "0"
    ]
},
{
    "DATA": "2016-01-25",
    "TOTAL": [
        "3",
        "2",
        "10",
        "0"
    ]
},
{
    "DATA": "2016-01-26",
    "TOTAL": [
        "1",
        "1",
        "4",
        "0"
    ]
},
{
    "DATA": "2016-01-27",
    "TOTAL": [
        "2",
        "1",
        "2",
        "0"
    ]
},
{
    "DATA": "2016-02-02",
    "TOTAL": [
        "1",
        "1",
        "1",
        "0"
    ]
},
{
    "DATA": "2016-02-10",
    "TOTAL": [
        "1",
        "1",
        "3",
        "0"
    ]
}
]

然后我将图表的数据构建为:

data.forEach(function(item) {
    var adata = item.DATA;
    var atotal = item.TOTAL;

    graphstr1 += '[new Date("' + adata + '"),' + atotal + '],';
});
graphstr1 = graphstr1.slice(0, -1);
console.log(graphstr1);

查看控制台,数据采用所需格式,但我总是在问题标题中得到错误

Dygraph代码:

g = new Dygraph(
    document.getElementById("graphdiv"), [
        graphstr1,
        /*[new Date("2016-01-22"), 7, 4, 20, 0],
        [new Date("2016-01-25"), 3, 2, 10, 0],
        [new Date("2016-01-26"), 1, 1, 4, 0],
        [new Date("2016-01-27"), 2, 1, 2, 0],
        [new Date("2016-02-02"), 1, 1, 1, 0],
        [new Date("2016-02-10"), 1, 1, 3, 0]*/

    ], {
        labels: ["x", "Registados", "Grávidas", "Com Filhos", "Sem Filhos"]
    }
);

1 个答案:

答案 0 :(得分:1)

为什么不在没有自制的stringifyed版本的情况下直接使用数组?



var data = [{ DATA: "2016-01-22", TOTAL: ["7", "4", "20", "0"] }, { DATA: "2016-01-25", TOTAL: ["3", "2", "10", "0"] }, { DATA: "2016-01-26", TOTAL: ["1", "1", "4", "0"] }, { DATA: "2016-01-27", TOTAL: ["2", "1", "2", "0"] }, { DATA: "2016-02-02", TOTAL: ["1", "1", "1", "0"] }, { DATA: "2016-02-10", TOTAL: ["1", "1", "3", "0"] }],
    converted = data.map(function (a) {
        return [new Date(a.DATA)].concat(a.TOTAL.map(Number));
    }),
    g = new Dygraph(
        document.getElementById("graphdiv"),
        converted, 
        { labels: ["x", "Registados", "Grávidas", "Com Filhos", "Sem Filhos"] });

<div id="graphdiv"></div>
<script type="text/javascript"
  src="https://cdnjs.cloudflare.com/ajax/libs/dygraph/1.1.1/dygraph-combined-dev.js"></script>
&#13;
&#13;
&#13;