Osman Mazinov Osman Mazinov - 1 year ago 126
Javascript Question

Display all stacked area data in popup on mouseover in d3.js

I want to show stacked area data on mouseover in a way it's implemented in the nvd3 example:
http://nvd3.org/examples/stackedArea.html but in pure d3.
Currently I'm displaying popup and vertical line on mouse over event, but wasn't able to display all data for stacks within the popup.
Coffescript is below.

verticalLine = svg.append('line')
'x1': 0,
'y1': 0,
'x2': 0,
'y2': height
.attr("stroke", "steelblue")
.attr('class', 'verticalLine')

svg.on "mousemove", () ->
xPos = d3.mouse(this)[0]
svg.select(".verticalLine").attr("transform", () ->
"translate(" + xPos + ",0)")

.style("font-size", "12px")
.style("opacity", .9)
.style("left", (d3.event.pageX + 5) + "px")
.style("top", (d3.event.pageY - 28) + "px")

svg.on "mouseout", () ->
.style "opacity", 0

Here is my fiddle

Answer Source

Looks like not only me struggled with the problem, so I'm posting my solution below. The idea is to get an intersection of the vertical line with x axis, i.e. find a target date, which will then allow us to grab all other fields related to that date. I used d3.bisector to find an index of the target date.

xPos = d3.mouse(this)[0]
bisectDate = d3.bisector((d) -> d.date).left
date = x.invert(xPos)
currentDateIndex = bisectDate(browsers[0].values, date)

Working code is here https://jsfiddle.net/ovvn/t44qovhg/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download