在D3中移动图例的Y位置 [英] Moving the Y position of a legend in D3

查看:187
本文介绍了在D3中移动图例的Y位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的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中独立设置每个图例(recttext).应该做的是将每个recttext放在g内,然后使用transformg作为组移动:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆