且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 D3 中附加多个矩形?

更新时间:2023-11-18 21:33:40

您已成功创建了额外的矩形,但不幸的是,它们都嵌套在前三个矩形内.如果您的浏览器上有 Web 开发者扩展程序,请选择其中一个矩形,然后查看源代码.

You're successfully creating extra rectangles, but unfortunately they are all nested inside the first three rectangles. If you have a web developer extension on your browser, select one of the rectangles and then view the source to see.

如果要附加矩形,而不是将它们嵌套在原始矩形内,则需要将两个矩形都附加到 g 节点.当您绑定数据并添加 g 节点时,将这些节点分配给一个变量:

If you want to append the rectangles, rather than nest them inside the original rectangle, you need to append both rectangles to your g node. When you bind the data and add your g nodes, assign those nodes to a variable:

var svg = d3.select("body").append("svg");

var nodes = svg.selectAll(".rect")
  .data([10,60,120])
  .enter()
  .append("g")
  .classed('rect', true)

然后您可以将两个矩形附加到 g 节点:

Then you can append the two rectangles to the g nodes:

// red rectangles
nodes.append("rect")
  .attr("width", 20)
  .attr("height", 20)
  .attr("x", 20)
  .attr("y", function(d) {return d})
  .attr("fill",  "red")

// blue ones
nodes.append("rect")
  .attr("width", 20)
  .attr("height", 20)
  .attr("x", 120)
  .attr("y", function(d) {return d})
  .attr("fill",  "blue")

请注意,如果您这样做:

Note that if you do this:

var nodes = svg.selectAll("rect")
  .data([10,60,120])
  .enter()
  .append("g")
  .append("rect")
  .attr("width", 20)
  .attr("height", 20)
  .attr("x", 20)
  .attr("y", function(d) {return d})
  .attr("fill",  "red")

nodes 将是对 rect 元素的引用,因为它们是最后添加的东西,并且任何附加到 nodes 的东西都会被添加内部 rect 元素.

nodes will be a reference to the rect elements, as they were the last thing added, and anything appended to nodes will be added inside the rect elements.

还要注意,你只需要将数据绑定到 g 元素;它被那些 g 元素的所有子节点自动继承.

Note also that you only need to bind the data once, to the g elements; it is automatically inherited by all the child nodes of those g elements.

这是完整的示例:

var svg = d3.select("body").append("svg");

var g = svg.selectAll(".rect")
  .data([10,60,120])
  .enter()
  .append("g")
  .classed('rect', true)

g.append("rect")
  .attr("width", 20)
  .attr("height", 20)
  .attr("x", 20)
  .attr("y", function(d) {return d})
  .attr("fill",  "red")

g.append("rect")
  .attr("width", 20)
  .attr("height", 20)
  .attr("x", 120)
  .attr("y", function(d) {return d})
  .attr("fill",  "blue")

<script src="https://d3js.org/d3.v5.js"></script>