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

后端 未结 1 563
野的像风
野的像风 2021-02-06 13:25

I\' ve created tooltips on multi-series line chart following the answer here. If I mouse over the last date as you can see in this picture:

the tooltips are ove

相关标签:
1条回答
  • 2021-02-06 14:00

    See changes here:

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

    Basically the tooltips need to be sorted by y position, and then we make sure neighbouring tooltips in that sort order are separated by a minimum distance (i picked 15px). The offset to the previously calculated y position is then added to the tooltip text. I also coloured the text to make them easier to tell which is which.

        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)+")";
            }
          ;
    
    0 讨论(0)
提交回复
热议问题