Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested SVG node creation in d3.js

I'v just started playing with d3js and find it strange that I have to create multiple selectors for each element I want to link to the background data structure for example separate selectors such as one for overlay text and one for rectangles to make an annotated bar graph.

svg.selectAll("rect")
.data(data)
.enter()
    .append("rect")
    .attr('y',function(d,i){return i*10;})
    .attr('height',10)
    .attr('width',function(d){return d.interestingValue})
    .fill('#00ff00');

svg.selectAll("text")
.data(data)
.enter()
    .append("text")
    .attr('y',function(d,i){return i*10;})
    .fill('#0000ff')
    .text(function(d){return d.interestingValue});

Is there a more convenient way of combining these into a single selection and enter() chain that creates both the rects and the text elements?

like image 464
Baxter Avatar asked Jul 05 '12 18:07

Baxter


1 Answers

Use a G (group) element. Use a single data-join to create the G elements, and then append your rect and text element. For example:

var g = svg.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d) { return "translate(0," + i * 10 + ")"; });

g.append("rect")
    .attr("height", 10)
    .attr("width", function(d) { return d.interestingValue; });

g.append("text")
    .text(function(d) { return d.interestingValue; });
like image 109
mbostock Avatar answered Oct 19 '22 23:10

mbostock