0

我正在按照本教程使用 D3.js 创建多个面积图,并且我想根据我的数据对其进行自定义。他的数据是:

Year, Variable1, Variable2, etc

我的数据是

YYYYMMDD, variable1, variable2, etc

我更改了这部分代码以将日期列转换为 Date 对象:

function createChart(data){
                            var countries = [];
                            var charts = [];
                            var maxDataPoint = 0;

                            /* Loop through first row and get each country 
                                and push it into an array to use later */
                            for (var prop in data[0]) {
                                if (data[0].hasOwnProperty(prop)) {
                                    if (prop != 'Day') {
                                        countries.push(prop);
                                    }
                                }
                            };

                            var countriesCount = countries.length;
                            var startYear = (data[0].Day).substr(0,4);
                            var endYear = (data[data.length - 1].Day).substr(0,4);
                            var chartHeight = height * (1 / countriesCount);

                            /* Let's make sure these are all numbers, 
                            we don't want javaScript thinking it's text 

                            Let's also figure out the maximum data point
                            We'll use this later to set the Y-Axis scale
                            */
                            data.forEach(function(d) {
                                for (var prop in d) {
                                    if (d.hasOwnProperty(prop)) {
                                        d[prop] = parseFloat(d[prop]);

                                        if (d[prop] > maxDataPoint) {
                                            maxDataPoint = d[prop];
                                        }
                                    }
                                }

                                // D3 needs a date object, let's convert it just one time
                                var y = (d.Day).substr(0,4),
                                        m = (d.Day).substr(4,2) - 1,
                                        d = (d.Day).substr(6,2);
                                    d.Day = new Date(y,m,d);

                            });

这是我的数据样本,大约有 400 行

Day NYTimes Guardian    The Peninsula   Gulf Times
20101201    1   8   2   0
20101203    3   9   2   0
20101205    6   10  4   1
20101207    2   9   5   1
20101209    1   3   7   0
20101211    12  8   6   0
20101213    3   4   3   0

没有显示图表,我只是得到一个空白页面,控制台上没有错误,看看这里。怎么了?

4

1 回答 1

0

在代码中的某处,Day 值正在从字符串 ("20101201") 转换为整数 (20101201)。然后,在尝试对整数使用 .substr() 时,您会收到 no method substr 错误。

尝试使用 .toString() 通过替换行将 var y 转换为字符串:

var y = (d.Day).substr(0,4)

var y = (d.Day).toString().substr(0,4)

或者考虑使用d3 的内置时间解析功能

于 2013-04-08T11:19:18.127 回答