score:8

Accepted answer

If you point a <use> element at a <rect> the width/height of the <use> are ignored according to the SVG specification

I recomment you put the <rect> in a <symbol>, and then have the use reference the symbol. That way the width/height of the use will apply to the rect. You probably want to make the rect's width/height 100% within the symbol.

In other words, something like this should work:

svg.append("defs").selectAll(".rectdef")
  .data(data).enter()
  .append("symbol")
  .attr("class", "rectdef")
  .attr("id", function (d, i){return "rect" + d.name;})
  .append("rect")
  .attr("x", 0)           // overridden below
  .attr("width", "100%")  // overridden below
  .attr("y", 0)           // overridden below
  .attr("height", function (d, i){return d.height});

svg.selectAll(".bar")
  .data(data).enter()
  .append("use")
  .attr("class", "bar")
  .attr("xlink:href",function (d){return "#rect"+d.type;})
  .attr("x", function(d) { return d.x })
  .attr("width", function (d) {return d.w;})  // this correctly adjusts width!
  .attr("y", function (d) {return 0;});

Related Query

More Query from same tag