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/*..*/
?
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
andtext
) independently across the whole svg. What should be done is that eachrect
andtext
is positioned within theg
and then theg
is moved as a group using atransform
:Full example here.