如何不使用 D3js 在多线图中显示缺失值

How not to display missing values in a multi line plot with D3js

我正在尝试使用 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 轴。

two lines plot

我不知道如何才能跳过 2005 年之前所有缺失的 null(或不确定?)值。如果我用 null 或 NaN 填充缺失的数据,我会收到以下错误:"d3.v4.min.js:2 Error: attribute d: Expected number, "M0 ,NaNL16,531L32,53……”。 有什么建议吗?

在行函数中检查是否设置了值,如果没有设置为未定义

d.value2 = (d.value2==="") ? null : +d.value2;