d3 svg rect height变为NaN

时间:2018-01-17 11:26:29

标签: javascript d3.js svg

我无法调试rect高度变为NaN的原因,下面是嵌入式代码。

相反,如果我只有.attr(“height”,yScale.bandwidth()),那么我会在HTML元素中看到正确的高度。

正确加载csv文件,因为我可以正确访问国家/地区和年份。

如果需要,我可以上传完整的代码。

var rHeight       = function(d) { return d.ratio;};

//// data is of CSV format :
//country,ratio,year
//United States,0.33,1924
//United States,0.33,1928
//United States,0.33,1932
//United States,0.0,1936
//United States,0.17,1948
//United States,0.2,1952
//::
//::
//

        
        
        
        // draw rectangles
        svg.selectAll(".bar")
            .data(rpc_data)
            .enter()
            .append("rect")
            .attr("class","bar")
            .attr("x",xMap)
            .attr("y",yMap)
            .attr("width",xScale.bandwidth())
            .attr("height",Math.floor((yScale.bandwidth())*rHeight) );

1 个答案:

答案 0 :(得分:2)

正如我们从您的代码段rHeight中看到的那样,它是一个函数,因此当您运行时:

Math.floor((yScale.bandwidth())*rHeight

number * function相同,结果为NaN(查看演示)。

console.log(1 * function() {});

你应该这样计算身高:

...
.attr("height", function(d){
  return Math.floor((yScale.bandwidth()) * rHeight(d)
}));