Free Man
Free Man

Reputation: 195

How to load txt files into D3.JS

I am trying to load a text (mydata.txt) file into d3.js. mydata.txt looks like this

name, age, Maria, 30, Fred, 50, Francis, 12

I used the follow code but I get this error at the console: "Unexpected value NaN parsing width attribute."

<script>
    //d3.txt("mydata.txt", function(data) {
    d3.csv("mydata.txt", function(data) {

    var canvas = d3.select("body")
                    .append("svg")
                    .attr("width",500)
                    .attr("height",500)

            canvas.selectAll("rect")
                    .data(data)
                    .enter()
                        .append("rect")
                        .attr("width",function(d){return d.age*10;})
                        .attr("height",48)
                        .attr("y",function(d,i){return i*50;})
                        .attr("fill", "blue");


})  
</script>

Upvotes: 2

Views: 7364

Answers (1)

mgold
mgold

Reputation: 6366

The likely cause is d.age*10. Multiplying a non-numeric string, or undefined, results in NaN. Try throwing .each(function(d){console.log(d)}) into the chain, right below append, and see if things are what you expect.

You can also try logging the entire data and see what it is.

I would also recommend using .csv rather than .txt. Beyond best practice, it's possible something weird is happening because of that.

Upvotes: 3

Related Questions