D3的格式数据

时间:2013-01-03 00:02:11

标签: php javascript d3.js

如何格式化我在d3.js中制作的图表的样本数据?

[
    [
        [
            "2",
            "2013-01-02 00:00:00+00"
        ],
        [
            "3",
            "2012-12-28 00:00:00+00"
        ],
        [
            "3",
            "2012-12-27 00:00:00+00"
        ],
        [
            "1",
            "2012-12-26 00:00:00+00"
        ],
        [
            "1",
            "2012-12-24 00:00:00+00"
        ],
        [
            "4",
            "2012-12-21 00:00:00+00"
        ],
        [
            "1",
            "2012-12-20 00:00:00+00"
        ]
    ],
    [
        [
            "1",
            "2012-12-27 00:00:00+00"
        ],
        [
            "2",
            "2012-12-21 00:00:00+00"
        ],
        [
            "2",
            "2012-12-18 00:00:00+00"
        ],
        [
            "1",
            "2012-12-17 00:00:00+00"
        ],
        [
            "1",
            "2012-11-27 00:00:00+00"
        ],
        [
            "1",
            "2012-11-03 00:00:00+00"
        ],
        [
            "1",
            "2012-10-27 00:00:00+00"
        ]
    ]
]

目前,当d3尝试解析此数据时,我的javascript控制台会在d3.v3.js:1033中为我提供Uncaught TypeError: Cannot use 'in' operator to search for '_dateElement' in NaN

似乎d3不想处理引号中的数字,没有引号使得json无效,我的ajax调用将不会返回,这意味着我将无法在d3函数中解析数组

我相信d3可以解析并格式化json,但我陷入了僵局。如何格式化此数据,日期对象将按升序排列为我的X轴,Y轴将是整数值的最大值

1 个答案:

答案 0 :(得分:2)

您需要将输入数组解析为输出数组,其数据格式为您想要的格式。正如C.Reed在评论中所说,使用parseInt将字符串转换为数字并使用d3.time.format将字符串转换为日期。 https://github.com/mbostock/d3/wiki/Time-Formatting

var date_in = "2013-01-02 00:00:00+00";
var format = d3.time.format("%Y-%m-%d 00:00:00+00");
var date_out = format.parse(date_in); 

(假设时间总是0)