如何避免多系列折线图d3.js的重叠工具提示

时间:2016-03-02 20:59:06

标签: javascript d3.js

我在answer here之后的多系列折线图上创建了工具提示。如果我将鼠标移到最后一个日期,如下图所示:

enter image description here

工具提示重叠。我想要的是当工具提示重叠时,将它们中的任何一个移动得更高或更低。我试图通过更改下面的代码来做到这一点。

   var beginning = 0,
        end = lines[i].getTotalLength(),
        target = null;
    //console.log(lines[i])             
    //console.log(end)
    while (true){
      target = Math.floor((beginning + end) / 2);
      pos = lines[i].getPointAtLength(target);
      if ((target === end || target === beginning) && pos.x !== mouse[0]) {
          break;
      }
      console.log(pos)
      if (pos.x > mouse[0])      end = target;
      else if (pos.x < mouse[0]) beginning = target;
      else break; //position found
    } 

我的想法是重新计算end。如果lines[0].getTotalLength()lines[1].getTotalLength()的减法小于或大于某个值,则更新end的值(例如end = end + 20)。但是我没有得到代码在这里工作。

有人知道怎么做吗?或者是否有更简单的方法来避免工具提示重叠?

1 个答案:

答案 0 :(得分:3)

请参阅此处的更改:

https://jsfiddle.net/fk6gfwjr/1/

基本上工具提示需要按y位置排序,然后我们确保该排序顺序中的相邻工具提示之间的距离最小(我选择15px)。然后将先前计算的y位置的偏移量添加到工具提示文本中。我还对文本进行了着色,以便更容易分辨哪个是哪个。

    var ypos = [];

    d3.selectAll(".mouse-per-line")
      .attr("transform", function(d, i) {
        // same code as before
        // ...
          // add position to an array
          ypos.push ({ind: i, y: pos.y, off: 0});

        return "translate(" + mouse[0] + "," + pos.y +")";
      })
      // sort this array by y positions, and make sure each is at least 15 pixels separated
      // from the last, calculate an offset from their current y value,
      // then resort by index
      .call(function(sel) {
        ypos.sort (function(a,b) { return a.y - b.y; });
        ypos.forEach (function(p,i) {
            if (i > 0) {
            var last = ypos[i-1].y;
           ypos[i].off = Math.max (0, (last + 15) - ypos[i].y);
            ypos[i].y += ypos[i].off;
          }
        })
        ypos.sort (function(a,b) { return a.ind - b.ind; });
      })
      // Use the offset to move the tip text from it's g element
      // don't want to move the circle too
      .select("text")
        .attr("transform", function(d,i) {
            return "translate (10,"+(3+ypos[i].off)+")";
        }
      ;