d3图表图例重叠

时间:2017-05-10 16:17:00

标签: javascript d3.js

有人可以帮我确定为什么我的这些特定传说会相互重叠吗?

这是我构建图例和间距的代码

  lSpace = WIDTH / dataGroup.length; 
vis.append("text")
.attr("x", (lSpace / 2) + i * lSpace)
.attr("y", HEIGHT)
.style("fill", function() { // Add the colours dynamically
  return d.color = color(d.key);
})
.attr("class", "legend")
.on('click', function() {
  var active = d.active ? false : true,
    opacity = active ? 0 : 1;
  // Hide or show the elements based on the ID
  d3.select("#tag" + d.key.replace(/[ )(]/g, ''))
    .style("opacity", opacity);
  // Update whether or not the elements are active
  d.active = active;
})
.text(d.key);

无论有多少数据传说,我一直在玩这个以获得相应的空间。不幸的是,不管我如何分隔传说,我得到一个与另一个重叠的传说。

这是一个小提琴: https://jsfiddle.net/9gzcbajx

1 个答案:

答案 0 :(得分:0)

我个人总是喜欢将图例包装到g组件中,并根据它的内容大小进行翻译。

这样可以节省更多空间。可读

关键代码是这个

var startX = 30;

legends.each(function(d, i, arr) {
  var wrapper = d3.select(this);  //this is g
  var text = wrapper.select('text');
  var bbox = text.node().getBBox();
  wrapper.attr('transform', 'translate(' + startX + ')');
  startX += bbox.width + 35;
})

我已更新您的fiddle

请注意,我已经从循环中解除了传说

相关问题