Moving the Y position of a legend in D3

ぃ、小莉子 提交于 2019-12-12 02:49:24

问题


I've made a legend for my choropleth map inspired off of this: http://bl.ocks.org/KoGor/5685876

The challenge is, I want to change the legend's location within my 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]; });

Changing the "x" location is easy, but the "y" location is the one I'm having trouble with. Why can't I just go .attr("y", 100, function/*..*/?

visual: click here


回答1:


I don't like the way your example code sets the position of the legend. He is setting each piece of the legend (both rect and text) independently across the whole svg. What should be done is that each rect and text is positioned within the g and then the g is moved as a group using a 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];
  });

Full example here.



来源:https://stackoverflow.com/questions/35785450/moving-the-y-position-of-a-legend-in-d3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!