Skip to content
Advertisement

d3 reads only first property of csv

Desired result

The test.csv needs to be fully accessed for data reading.

Current State

I have moved some of the values around within the file for different test cases. It appears that the first entry of each row, regardless of type, is the only one that can be returned. At no point have I got any console errors.

The CSV

started, numb, eggs, waffles, name, cost
False, 34, "over easy", True, elle, 22
True, 24, "scrambled", False, belle, 22
False, 10, "fortunate", False, jake, 20

Using the line 3 console.log(data) reveals that the objects have been successfully loaded with the appropriate key/values.

[1]Object
" cost": " 22"
" eggs": " "scrambled""
" name": " belle"
" waffles": " False"
numb: "24"

(d3 added quotes around everything, looks like JSON. Have they been cast as string, or are quotes just delimiters?)

d3.js

d3.csv("test.csv", function(data) {

    console.log(data);

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

    canv.selectAll("rect")
        .data(data)
        .enter()
            .append("rect")
            .attr("height", 15)
            .attr("width", function(d) { return d.numb})
            .attr("y", function(d, i) {return 50 + i * 20})
            .attr("fill", "orange")

    canv.selectAll("text")
        .data(data)
        .enter()
            .append("text")
            .attr("y", function(d, i) {return 50 + i * 20})
            .text( function(d) {return d.started;})
    });

In this case, the started property prints on screen but the rectangles have width 0.

When numb is the first entry for each row, the rects have appropriate widths, but no other attributes print.

What is the error?

Advertisement

Answer

Your first problem is that your csv file has spaces after each comma. This is a mal-formed file, in a true csv file commas are the delimiter NOT comma-space.

Second problem is that d3 won’t autoconvert your data to specific types. Usually you provide a row conversion function to do convert data to proper formats. Yours might look like this:

d3.csv("test.csv", function(d) {

  return {
    started: d.started === 'True',
    numb: +d.numb,
    eggs: d.eggs,
    waffles: d.waffles === 'True',
    name: d.name,
    cost: +d.cost
  };

}, function(data) {

  console.log(data); 

  ...

Fixing these problems up and your visualization start to take shape

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement