This should be a fairly simple D3 question. I’m binding data to some circles, here is the data:
var linedata = [{ x:10, y:20},{x:5, y:30}];
And here are the circles:
var line = d3.svg.line().x(function(d) {
return x(d.x);
}).y(function(d) {
return y(d.y);
});
context.selectAll(".dot")
.data(linedata).enter()
.append("circle")
.attr("class", "dot")
.attr("cx", line.x())
.attr("cy", line.y())
.attr("r", 2);
However, if I want to change the data and code to use some data keys, so that circles have classes attached:
var mydata = [{ name: 'LHR', data: [{ x:10, y:20}, {x:5, y:15} ], { name: 'SFO', data : [{x:5, y:30}, {x:4, y:8}] }];
I know how to edit the class attribute to use the data key, but how do I edit the cx and cy attributes?
context.selectAll(".dot")
.data(mydata).enter()
.append("circle")
.attr("class", function(d) { return "dot " + d.name; })
.attr("cx", line.x())
.attr("cy", line.y())
.attr("r", 2);
I’ve tried the following, but it doesn’t work:
.attr("cx", function(d) { return line.x(d.data); })
That seems to assign the function itself to the cx attribute. What am I doing wrong?
Figured it out, with help from Alex’s answer – I should pass the array item directly, and I shouldn’t be using the
linefunction at all. Instead: