Osman Mazinov
Osman Mazinov

Reputation: 1446

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')
  .attr({
    '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)")

tooltip.transition()
  .duration(200)
  .style("font-size", "12px")
  .style("opacity", .9)
tooltip.html("Info")
  .style("left", (d3.event.pageX + 5) + "px")
  .style("top", (d3.event.pageY - 28) + "px")

svg.on "mouseout", () ->
  tooltip.transition()
    .duration(500)
    .style "opacity", 0

Here is my fiddle

Upvotes: 0

Views: 767

Answers (1)

Osman Mazinov
Osman Mazinov

Reputation: 1446

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/

Upvotes: 1

Related Questions