我正在尝试使用 D3js 从 tsv 文件中绘制两行。一个系列已完成,第二个系列的值仅从 2005 年开始。
year value1 value2
2000 8956355
2001 8924704
2002 8865723
2003 8747717
2004 8701521
2004 8701521
2005 8607147 11380809
2006 8551259 10672554
2007 8513818 10394369
2008 8462607 10297716
2009 8448535 9998783
2010 8411177 9988697
2011 8024205 9491908
2012 7920080 8725402
2013 7911208 8668111
2014 7807984 8274928
2015 7747598 8027083
2016 7575879 7779103
我的两行代码如下:
var line1 = d3.line()
.x(function(d) { return x1(d.year); })
.y(function(d) { return y1(d.value1); });
var line2 = d3.line()
.defined(function(d) { return d.value2 != undefined; })
.x(function(d) { return x1(d.year); })
.y(function(d) { return y1(d.value2); });
d3.tsv("js/plots/nitrogen-fertilisers.tsv"
, function(d) {
d.value1 = +d.value1;
d.value2 = +d.value2;
return d;
}
fw1.append("path")
.datum(data)
.attr("class", "line")
.attr("fill", "none")
.attr("stroke", "#004494")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line1);
fw1.append("path")
.datum(data)
.attr("class", "line")
.attr("fill", "none")
.attr("stroke", "#7FA1C9")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line2);
显示了两条线,但如图所示,第二个系列不是从 2005 年开始,而是从系列的开头开始,其中一段来自 x 轴。
我不知道如何在 2005 年之前跳过所有缺失的 null(或不确定?)值。如果我用 null 或 NaN 填充缺失的数据,我会得到以下错误:“d3.v4.min.js:2 Error :属性 d:预期数字,“M0,NaNL16,531L32,53...”。有什么建议吗?
在行函数中检查值是否已设置,如果未将其设置为未定义
d.value2 = (d.value2==="") ? null : +d.value2;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句