How To Avoid Overlapping Tooltips Of Multi-series Line Chart D3.js
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 overlapping. What I wan
Solution 1:
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)+")";
}
;
Post a Comment for "How To Avoid Overlapping Tooltips Of Multi-series Line Chart D3.js"