6

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?

1 Answer 1

20

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; });
Sign up to request clarification or add additional context in comments.

3 Comments

And it comes from the man himself! thanks for the response and a great library.
I wasn't able to get this to work for dynamic data updates unless I set data bindings on the sub-elements with .data(). With the above code, an update to the data bound to g re-drew the elements within the g using the originally bound data.
Right; binding data to parent elements doesn’t automatically propagate it to children. You need to perform one of the following in order to propagate data from parent to child: data, datum, select, append or insert. See also my tutorial on nested selections.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.