Kagimura
Kagimura

Reputation: 417

Grouping two g with the same class in D3

How would I group two g's in with the same class

<g transform="translate(30,20)">
    <g class="y axis" transform="translate(670 ,0)" style="fill: red;">
       <g class="tick" transform="translate(0,445)" style="opacity: 1;">
          <line x2="6" y2="0"></line>
          <text dy=".32em" x="9" y="0" style="text-anchor: start;">0</text>
       </g>
       <g class="tick" transform="translate(0,356)" style="opacity: 1;">
          <line x2="6" y2="0"></line>
          <text dy=".32em" x="9" y="0" style="text-anchor: start;">20</text>
       </g>
       <g class="tick" transform="translate(0,267)" style="opacity: 1;">
          <line x2="6" y2="0"></line>
          <text dy=".32em" x="9" y="0" style="text-anchor: start;">40</text>
       </g>
    </g>
    <g class="legend" transform="translate(0,0)">
       <rect x="752" width="18" height="18" style="fill: rgb(208, 116, 60);"></rect>
       <text x="746" y="9" dy=".35em" style="text-anchor: end;">Boys</text>
    </g>
    <g class="legend" transform="translate(0,20)">
       <rect x="752" width="18" height="18" style="fill: rgb(160, 93, 86);"></rect>
       <text x="746" y="9" dy=".35em" style="text-anchor: end;">Girls</text>
    </g>
 </g>

I want to wrap the two g's with class name legend inside another g with a class name wrapper legend

here is the current code for the legends

  var legend = svg.selectAll(".legend")
      .data(color.domain().slice().reverse())
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

Upvotes: 1

Views: 251

Answers (1)

SmokeyShakers
SmokeyShakers

Reputation: 3412

Just append a g beforehand:

  var legend = svg.append('g')
      .classed('wrapper-legend', true)
      .selectAll(".legend")
      .data(color.domain().slice().reverse())
      .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

Note, in this case, your variable legend will still be the selection of the two g.legend elements, not the g.wrapper-legend

Upvotes: 2

Related Questions