我尝试使用d3重现多线图的this example。 我说我很少知道d3,我刚刚开始使用它。
我会得到一张图表,其中x轴为日期(1995,1996,...,2010),y轴为0~3000。 表示csv中各种数据类别的行。
这是我的代码的一部分:
// Get the data
d3.csv("./data/df_out.csv", function(error, data) {
data.forEach(function(d) {
d.year = d.year; //parseDate(d.year);
d.value = +d.value;
});
// Scale the range of the data
x.domain([1995, 2010]);
y.domain([0, 3000]);
// Nest the entries by death
var dataNest = d3.nest()
.key(function(d) { return d.death;})
.entries(data);
// Loop through each symbol / key
dataNest.forEach(function(d) {
svg.append("path")
.attr("class", "line")
.attr("d", valueline(d.values));
});
});
当我运行它时,我收到错误:
错误:属性d:预期数字," MNaN,NaNLNaN,NaNL ..." .attrConstant @ d3.js:663(匿名函数)@ d3.js:962d3_selection_each @ d3.js :968d3_selectionPrototype.each @ d3.js:961d3_selectionPrototype.attr @ d3.js:652(匿名函数)@ script.js:56(匿名函数)@ script.js:53(匿名函数)@ d3.js:1996event @ d3 .js:504对应@ d3.js:1949
问题是nest
功能,我不明白为什么。
有人可以帮助我吗?
这里是整个代码:http://plnkr.co/edit/kiU1KwdvsC7e1rrjAuCM?p=preview。
非常感谢。
答案 0 :(得分:4)
首先,您的CSV不正确:
",""year"",""death"",""value"""
"1,2003,""Acute poliomyelitis"",0"
"2,2006,""Acute poliomyelitis"",0"
"3,2007,""Acute poliomyelitis"",0"
"4,2008,""Acute poliomyelitis"",0"
"5,2009,""Acute poliomyelitis"",0"
"6,2010,""Acute poliomyelitis"",0"
"7,1995,""Acute poliomyelitis"",0"
"8,1996,""Acute poliomyelitis"",0"
"9,1997,""Acute poliomyelitis"",0"
"10,1998,""Acute poliomyelitis"",0"
"11,1999,""Acute poliomyelitis"",0"
"12,2000,""Acute poliomyelitis"",0"
"13,2001,""Acute poliomyelitis"",0"
"14,2002,""Acute poliomyelitis"",0"
应该是(删除了双引号)
,year,death,value
1,2003,Acute poliomyelitis,0
2,2006,Acute poliomyelitis,0
3,2007,Acute poliomyelitis,0
4,2008,Acute poliomyelitis,0
5,2009,Acute poliomyelitis,0
6,2010,Acute poliomyelitis,0
7,1995,Acute poliomyelitis,0
8,1996,Acute poliomyelitis,0
9,1997,Acute poliomyelitis,0
10,1998,Acute poliomyelitis,0
11,1999,Acute poliomyelitis,0
12,2000,Acute poliomyelitis,0
13,2001,Acute poliomyelitis,0
14,2002,Acute poliomyelitis,0
其次,
你需要像这样解析日期:
data.forEach(function(d) {
d.year = parseDate(d.year);
d.value = +d.value;
});
第三
像这样设置x域:
x.domain(d3.extent(data, function(d){return d.year}));
最后在传递行数据之前对数据进行排序w.r.t.年。
// Loop through each symbol / key
dataNest.forEach(function(d, i) {
d.values = d.values.sort(function(a,b){return a.year -b.year});//sort by year
svg.append("path")
.attr("class", "line")
.attr("d", valueline(d.values))
.style("stroke", color(i)) ;
});
工作代码here