繁体   English   中英

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

[英]How to avoid overlapping tooltips of multi-series line chart d3.js

我按照这里答案在多系列折线图上创建了工具提示。 如果我将鼠标悬停在最后一个日期,您可以在此图片中看到:

在此输入图像描述

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

   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)。但我没有'让代码在这里工作。

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

查看此处的更改:

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)+")";
        }
      ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM