D3.js多区域图表不起作用

时间:2013-04-08 06:34:56

标签: javascript d3.js data-visualization

我正在关注此tutorial以使用D3.js创建多个区域图表,并且我想将其自定义为我的数据。 他的数据是:

Year, Variable1, Variable2, etc

我的数据是

YYYYMMDD, variable1, variable2, etc

我更改了这部分代码,将date列转换为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

没有显示图表,我只是得到一个空白页面并且控制台上没有错误,请查看here。有什么问题?

1 个答案:

答案 0 :(得分:0)

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

尝试使用.toString()通过替换line:

将var y转换为字符串
var y = (d.Day).substr(0,4)

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

或者考虑使用d3's built in time parsing functions