D3散点图图例重叠

时间:2019-05-17 14:36:06

标签: d3.js legend

我有一个散点图,可以很好地工作,但是我添加的图例与图表重叠。我当前的方法是使图表DIV为宽度的70%,并让图例占据剩余的30%。由于某些原因,即使有HTML,图例也不会显示在屏幕上。

这是我最初的问题的链接:http://jsfiddle.net/chp5a09e/373/

以下是我当前正在尝试的链接:http://jsfiddle.net/chp5a09e/372/

var legend = d3.select("#legend").append("svg")
    .attr("width", $("#legend").width())
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  legend.selectAll(".legend")
    .data(color.domain())
    .enter().append("g")
    .attr("class", "legend")
    .attr("transform", function(d, i) {
      return "translate(0," + i * 20 + ")";
    });

  legend.append("rect")
    .attr("x", width - 12)
    .attr("width", 12)
    .attr("height", 12)
    .style("fill", function(d) {
      return color(d);
    })
    .on("click", function(d) {
      d3.selectAll(".symbol").style("opacity", 1)

      if (clicked !== d) {
        d3.selectAll(".symbol")
          .filter(function(e) {
            return e.items[columns.indexOf("Channel")] !== d;
          })
          .style("opacity", 0.1)
        clicked = d
      } else {
        clicked = ""
      }
    });

  legend.append("text")
    .attr("x", width - 16)
    .attr("y", 6)
    .attr("dy", ".35em")
    .style("text-anchor", "end")
    .text(function(d) {
      return d;
    });

1 个答案:

答案 0 :(得分:1)

  

有HTML

仅存在(g)组元素,而它们本身也不可见。用您的原始代码

var legend = svg.selectAll(".legend")
    .data(color.domain())
    .enter().append("g")
    ...

  legend.append("rect")

这里的legend是多个g.legend元素的选择,因此rect被附加到每个元素上,并且可以访问绑定到父g的基准。但是,在您的新代码中

var legend = d3.select("#legend").append("svg")
    ...
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  legend.selectAll(".legend")
    .data(color.domain())
    .enter().append("g")
    ...;

  legend.append("rect")

此处的legend仅指包含整个图例的单个g元素。您的legend.selectAll(".legend")不会保存到变量中,因此,在链中您可以正确设置类和转换属性时,请不要使用它来将rect附加到变量上-再次,legend指的是外面的单个g容器。


可能的解决方案:

var legendCnt = d3.select("#legend").append("svg")
    .attr("width", $("#legend").width())
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var legend = legendCnt.selectAll(".legend")
    .data(color.domain())
...

您会发现需要删除或降低文本和矩形的x属性,因为0现在位于图例的开头,而不是图表的开头

相关问题