首页 > 解决方案 > 使用 D3js 在线图上显示标签时出错

问题描述

我有一个两线图,点从带有 D3js 的 tsv 文件中淹没。我想在点附近显示标签。tsv文件不完整,缺少一些值,如下:

year    value1    value2
....
2000    8956355 
2001    8924704 
2002    8865723 
2003    8747717 
2004    8701521 
2004    8701521 
2005        11380809
2006        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

我用于显示第一行、点和标签的代码如下(第二行相同):

// line1
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);
// dots for line1
fw1.selectAll(".dot")
        .data(data)
            .enter()
            .append("circle")
                .attr("class", "dot")
                .style("stroke", "#004494")
                .attr("cx", function(d) { return x1(d.year); })
                .attr("cy", function(d) { return y1(d.value1); })
                .attr("r", 3.5)
fw1.append("g")
    .classed('labels-group', true)
    .selectAll('text')
    .data(data)
    .enter()
    .append('text')
        .classed('textlbl', true)
        .attr({ 'x': function(d) { return x1(d.year);},
                    'y': function(d) { return y1(d.value1);}
        })
    .text(function(d) { return d.value1 = (d.value1==="") ? null : +d.value1; });

两行和点正确显示,但代码返回以下标签的错误“未捕获的类型错误:无法读取 null 的属性'文本'”。

标签: d3.jsplotlabelmissing-dataline-plot

解决方案


推荐阅读