簡體   English   中英

如何不使用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軸。

兩線圖

我不知道如何在2005年之前跳過所有缺失的null(或不確定的?)值。如果我用null或NaN填充缺失的數據,則會收到以下錯誤:“ d3.v4.min.js:2錯誤:屬性d:預期數字“ M0,NaNL16,531L32,53…”。有什么建議嗎?

在行函數中檢查是否設置了該值(如果未將其設置為undefined)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM