user1167650
user1167650

Reputation: 3207

d3.js nested selections

I'm trying to create <g> elements foreach datapoint I have and add in a couple different <text> elements to each <g> element based on the current datapoint. I've tried something like:

var g = vis.selectAll("g").data(dd,function(d){ return d.data.name+d.x+d.y+d.s; });

    var gs = g.enter().append("g");         
        g.exit().remove();

    var t = gs.selectAll("text").data(function(d) { console.log(d); return d; });
    t.enter().append("text").attr("x",function(d){ return d.x+d.s/2; })
        .attr("y",function(d){ return d.y+d.s/4; })
        .attr("font-family","Verdana")
        .attr("font-size","9")          
        .attr("text-anchor","middle")
        .text(function(d){ return d.data.name; });      

    t.attr("x",function(d){ return d.x+d.s/2; })
        .attr("y",function(d){ return d.y+d.s/4; })
        .attr("font-family","Verdana")
        .attr("font-size","9")          
        .attr("text-anchor","middle")
        .text(function(d){ return d.data.name; });      

    t.exit().remove();

But all I get are a set of empty <g> elements. Am I doing something obviously wrong?

Upvotes: 1

Views: 2321

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

Nested selections assume some kind of nested data, e.g. a matrix. Your individual data elements are not arrays, so the second call to .data() doesn't do anything. Have a look at the tutorial on nested selections for more details.

It's not clear to me why you want nested selections in your case. You're adding a text element that displays the name for a data point, so you shouldn't need the second (nested) selection. The easiest way to fix it (at least syntactically) however should be to change each element of dd into a single-element array.

Upvotes: 5

Related Questions