在 D3 中移动图例的 Y 位置

Moving the Y position of a legend in D3

我受此启发为我的等值线图制作了一个图例: http://bl.ocks.org/KoGor/5685876

挑战是,我想在 canvas/svg 中更改图例的位置。

var legend = svg.selectAll("g.legend")
.data(ext_color_domain)
.enter().append("g")
.attr("class", "legend");

var ls_w = 20, ls_h = 20;

legend.append("rect")
.attr("x", 20)
.attr("y", function(d, i){ return height - (i*ls_h) - 2*ls_h;})
.attr("width", ls_w)
.attr("height", ls_h)
.style("fill", function(d, i) { return color(d); })
.style("opacity", 0.8);

legend.append("text")
.attr("x", 50)
.attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
.text(function(d, i){ return legend_labels[i]; });

更改 "x" 位置很容易,但 "y" 位置是我遇到的问题。为什么我不能直接去 .attr("y", 100, function/*..*/?

visual: click here

我不喜欢您的示例代码设置图例位置的方式。他正在整个 svg 中独立设置图例的每一部分(recttext)。应该做的是每个 recttext 都位于 g 内,然后 g 使用 transform 作为一个组移动:

var legend = svg.selectAll("g.legend")
  .data(ext_color_domain)
  .enter().append("g")
  .attr("class", "legend")
  .attr('transform', 'translate(0,0)'); //<-- where does the group go

var ls_w = 20,
  ls_h = 20;

legend.append("rect")
  .attr("x", 20)
  .attr("y", function(d, i) {
    return (i * ls_h) - 2 * ls_h; //<-- position in group
  })
  .attr("width", ls_w)
  .attr("height", ls_h)
  .style("fill", function(d, i) {
    return color(d);
  })
  .style("opacity", 0.8);

legend.append("text")
  .attr("x", 50)
  .attr("y", function(d, i) {
    return (i * ls_h) - ls_h - 4; /<-- position in group
  })
  .text(function(d, i) {
    return legend_labels[i];
  });

完整示例 here.