2016-03-02 76 views
3

我在answer here之后创建了多系列折线图上的工具提示。如果我将鼠标放在最后日期,你可以在这个图片中看到:如何避免重叠的多系列折线图工具提示d3.js

enter image description here

的提示是重叠的。我想要的是当工具提示重叠时,将它们中的任何一个稍微更高或更低。我试图通过更改下面的代码来做到这一点。我的想法是重新计算end。如果lines[0].getTotalLength()lines[1].getTotalLength()的减法小于或大于一个值,则更新结束值(例如,结束=结束+ 20)。但是我没有在这里得到代码工作。

有谁知道如何做到这一点?或者是否有避免工具提示重叠的更简单的方法?

回答

3

看到这里的变化:

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

基本上需要通过y位置进行排序的提示,然后我们做出那种为了确保周边提示通过的最小距离是分开的(我捡15像素) 。然后将以前计算的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)+")"; 
     } 
     ;