Richard
Richard

Reputation: 65530

Basic D3.js: how to use joins within a function?

I'm getting to grips with D3.js. I would like to write a function that draws one set of dots with one set of data, then another set of dots with another set of data.

I have written this, but the second set of dots is over-writing the first set of dots! How can I rewrite it without the selectAll so that I correctly end up with two sets of dots?

function drawDots(mydata) { 
  focus.selectAll(".dot").data(mydata)
    .enter().append("circle")
    .attr("class", "dot")
    .attr("cx", line.x())
    .attr("cy", line.y())
    .attr("r", 3.5);
}
drawDots(data[0]);
drawDots(data[1]);

(NB: This is a simplification. Basically I want to know how to use .enter() with a function call.)

Upvotes: 1

Views: 186

Answers (2)

dMb
dMb

Reputation: 9337

you need to give two sets of data distinct class names. Right now both get tagged with the same class (".dot"), but if they represent different sets, you also need to be able to distinguish between them. E.g.:

function drawDots(mydata, name) { 
  focus.selectAll(".dot"+"."+name).data(mydata)
    .enter().append("circle")
    .attr("class", "dot" + " " + name)
    .attr("cx", line.x())
    .attr("cy", line.y())
    .attr("r", 3.5);
}
drawDots(data[0], "set1");
drawDots(data[1], "set2");

Upvotes: 2

John Russell
John Russell

Reputation: 1165

I've only used d3js for building force graphs, but I think in your case you need to add the nodes first to the visualization, then invoke enter() and then fetch what is in the graph.

function drawDots(mydata) 
{ 
  myD3Object.nodes(myData).start();
  focus.selectAll(".dot").data(myD3Object.nodes())
  .enter().append("circle")
  .attr("class", "dot")
  .attr("cx", line.x())
  .attr("cy", line.y())
  .attr("r", 3.5);
}

Upvotes: 1

Related Questions