How to always always keep the rollover text of line d3 always visible?

I am using d3 v4. When someone rolls over my line chart, I want the display to show information about the point on the graph where they roll, so I turned on this

svg.append("rect") .attr("class", "overlay") .attr("width", width) .attr("height", height) .on("mouseover", function() { focus.style("display", null); }) .on("mouseout", function() { focus.style("display", "none"); }) .on("mousemove", mousemove); function mousemove() { var x0 = x.invert(d3.mouse(this)[0]), i = bisectDate(data, x0, 1), d0 = data[i - 1], d1 = data[i], d = x0 - d0.date > d1.date - x0 ? d1 : d0; focus.attr("transform", "translate(" + x(d.index_date) + "," + y(d.value) + ")"); focus.select("text").text(d.value).append("tspan") .attr("x", 10).attr("dy", "1.5em").text(formatDate(d.index_date)); var bbox = focus.select("text").node().getBBox(); rect.attr("width", bbox.width + 4).attr("height", bbox.height + 4); } 

The problem is that as you are more and more right from my line chart, the information begins to be cut - https://jsfiddle.net/rgw12x8d/2/ . How can I set things up so that even if you go over a point in the far right corner, the info window remains completely visible?

+5
source share
1 answer

You can run a test on d3.mouse(this)[0]) to see if it is on the right side of the chart, for example, greater than width/2

If so, run x in translation to x(d.index_date) - (bbox.width + 4) , which will shift the field to the left of the mouse position

For instance:

 function mousemove() { var x0 = x.invert(d3.mouse(this)[0]), i = bisectDate(data, x0, 1), d0 = data[i - 1], d1 = data[i], d = x0 - d0.date > d1.date - x0 ? d1 : d0; focus.select("text").text(d.value).append("tspan") .attr("x", 10).attr("dy", "1.5em").text(d3.timeFormat("%Y-%b-%d")(d.index_date)); var bbox = focus.select("text").node().getBBox(); var rectWidth = bbox.width + 4 rect.attr("width", rectWidth).attr("height", bbox.height + 4) var translateX = d3.mouse(this)[0] > (width/2) ? x(d.index_date) - rectWidth : x(d.index_date); focus.attr("transform", "translate(" + translateX + "," + y(d.value) + ")"); 

}

You will also need to adjust the cx circle, which I am not included here.

+2
source

Source: https://habr.com/ru/post/1270900/


All Articles