在 d3.js 中创建嵌套的 SVG 节点

Nested SVG node creation in d3.js

本文关键字:SVG 节点 嵌套 创建 d3 js      更新时间:2023-09-26

我刚开始使用 d3js,发现奇怪的是我必须为要链接到背景数据结构的每个元素创建多个选择器,例如单独的选择器,例如一个用于叠加文本,一个用于矩形以制作带注释的条形图。

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});

有没有更方便的方法将它们组合成一个创建矩形和文本元素的选择和 enter() 链?

使用 G(组)元素。使用单个数据联接创建 G 元素,然后追加矩形和文本元素。例如:

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; });