D3.js多区域图表不工作

D3.js multiple area chart not working

本文关键字:工作 区域 js D3      更新时间:2023-09-26

我正在使用D3.js创建多个面积图,我想将其自定义为我的数据。他的数据是:

Year, Variable1, Variable2, etc

My data is

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

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

在代码的某个地方,Day值正在从字符串("20101201")转换为整数(20101201)。当你尝试在整数上使用.substr()时,你会得到一个no method substr错误。

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

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

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

或者考虑使用d3的内置时间解析函数