错误:<circle>属性cx:预期长度,“NaN”和错误:<circle>属性cy:预期长度,“NaN”

时间:2018-05-05 12:37:28

标签: d3.js

这是我的代码

// Importing CSV file
d3.csv("Dataset.csv", function (error, data) {

    //output error if csv file failed to load
    if(error){
        console.log(error);
    } else {
        console.log(data); //show loaded data to console



        //linear scaling the datasets.
        var xscale = d3.scaleLinear()
            .domain([d3.min(function (d) {
                return d.Surface_temperature;
            }), d3.max(function (d) {
                return d.Surface_temperature;
            })])
            .range([0, w - 100]);

        var yscale = d3.scaleLinear()
            .domain([d3.min(function (d) {
                return d.habitable_temperature;
            }), d3.max(function (d) {
                return d.habitable_temperature;
            })])
            .range([h - 200, 0]);



        // appended svg with its attributes inside the body element
        var mysvg = d3.select("body")
            .append("svg")
            .attr("width",w)
            .attr("height",h);


        // appending svg circle elements
        mysvg.selectAll("circle")
        .data(data)
        .enter()
        .append("circle")
        .attr("cx", function (d) {
            return xscale(d.Surface_temperature);
        })
        .attr("cy", function (d) {
            return yscale(d.habitable_temperature);
        })
        .attr("r", 10)

    }

});

我收到错误:属性cx:预期长度,“NaN”请帮助我。我试图几乎到处检查,但无法解决这个问题。

1 个答案:

答案 0 :(得分:2)

您没有正确使用d3.mind3.max

这两个函数都使用数据来计算最小值和最大值,以及可选的访问器函数。您只传递了一个访问函数。

您的尺度应设置如下(请注意,我将data传递给d3.mind3.max):

    var xscale = d3.scaleLinear()
        .domain([d3.min(data, function (d) {
            return d.Surface_temperature;
        }), d3.max(data, function (d) {
            return d.Surface_temperature;
        })])
        .range([0, w - 100]);

    var yscale = d3.scaleLinear()
        .domain([d3.min(data, function (d) {
            return d.habitable_temperature;
        }), d3.max(data, function (d) {
            return d.habitable_temperature;
        })])
        .range([h - 200, 0]);

顺便说一句,为了让其他人在将来更容易为您提供帮助,请同时提供示例数据文件。它不必是一个包含数千行的真实文件,只需要一个简单的行就可以完成三行。为了重现你的问题,我编写了一个测试文件,当然我假设你的数据文件没有问题。