在D3中移动图例的Y位置 [英] Moving the Y position of a legend in D3
问题描述
我为我的choropleth地图做了一个传奇,它的灵感来自于此: http://bl.ocks.org/KoGor/5685876
I've made a legend for my choropleth map inspired off of this: http://bl.ocks.org/KoGor/5685876
挑战在于,我想在我的画布/svg中更改图例的位置.
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]; });
更改"x"位置很容易,但是"y"位置是我遇到的麻烦.为什么我不能只去.attr("y", 100, function/*..*/
?
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/*..*/
?
推荐答案
我不喜欢您的示例代码设置图例位置的方式.他正在整个svg中独立设置每个图例(rect
和text
).应该做的是将每个rect
和text
放在g
内,然后使用transform
将g
作为组移动:
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];
});
完整示例此处.
这篇关于在D3中移动图例的Y位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!