I’ve been using D3plus the last couple of weeks and discovered a couple of interesting things. Managing the raw data is definitely where a lot of the effort went. The rest of the time was spent trying to make sure the right structure was being passed to d3.

I started with just a div where d3 would draw the viz:

<div id="viz"></div>

All other work happened inside the data injester:

d3.json('/data.json', function(error, ourdata) {
  // Do stuff.
}

The first error I saw was about missing data for certain attributes. So I had to add a way to filter those items:

// Ignore rows with null Year value.
ourdata = ourdata.filter(function(d) {
  return d.year != null
})

Then I discovered we have to explicitely describe which items are string and which are numbers:

// Convert all columns except "state" to numnbers.
ourdata.forEach(function(d) {
  d3.keys(d).forEach(function(k) {
    if (k != 'state') {
      d[k] = +d[k]
    }
  })
})

This provided a structure that looks something like this:

data = [
  {"year": 1991, "state":"Alabama", "count": 15},
  {"year": 1992, "state":"Arkansas", "count": 20},
  {"year": 1993, "state":"Arizona", "count": 30},
  {"year": 1994, "state":"Colorado", "count": 60}
]

If we wanted to see a linegraph of count per year (regardless of “State”), one would assume the following would work:

var visualization = d3plus.viz()
  .container("#viz")
  .data(data)
  .type("line")
  .id("year")
  .y("value")
  .x("year")
  .draw()

However, this would just render a scatter plot, with a dot for each count/year value. In order to make this a linegraph, the id must be a third value (something other than year or count). We can pass state, but that would draw a separate line for each state. So what we can do is create another attribute (i.e., annual count) that is the same across each element so we have a single graph for year/count.

Resources