d3: Coloring Multiple Lines from Nested Data

Posted by diet_coke on Stack Overflow See other posts from Stack Overflow or by diet_coke
Published on 2012-04-08T23:05:38Z Indexed on 2012/04/08 23:29 UTC
Read the original article Hit count: 217

Filed under:
|
|

I'm currently assembling some line graphs with circles at the datapoints from arrays of JSON objects formatted like so:

var data = [{
    "name": "metric1",
    "datapoints": [
        [10.0, 1333519140],
        [48.0, 1333519200]
    ]
}, {
    "name": "metric2",
    "datapoints": [
        [48.0, 1333519200],
        [12.0, 1333519260]
    ]
}]

I want to have a color for each metric, so I'm trying to color them based on the index of the object within the array data. The code I have currently for just placing the circles looks like:

// We bind an svg group to each metric.
var metric_groups = this.vis.selectAll("g.metric_group")
  .data(data).enter()
  .append("g")
    .attr("class", "metric_group");

// Then bind a circle for each datapoint.
var circles = metric_groups.selectAll("circle")
.data(function(d) { return d.datapoints; });

circles.enter().append("circle")
  .attr("r", 3.5);

Now if I change that last bit to something like:

circles.enter().append("circle")
  .attr("r", 3.5);
  .style("fill", function(d,i) { return i%2 ? "red" : "blue"; }

I get alternating red and blue circles, as could be expected.
Taking some advice from Nested Selections : 'Nesting and Index', I tried:

circles.enter().append("circle")
  .attr("r", 3.5);
  .style("fill", function(d,i,j) { return j%2 ? "red" : "blue"; }

Which doesn't work (j is undefined), presumably because we are in the named property datapoints, rather than an array element. How might I go about doing the coloring that I want without changing my data structure? Thanks!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about d3.js