Cerberus
Cerberus

Reputation: 111

Generating tool-tip for dynamic data in D3

I have a scatter plot similar to: http://plnkr.co/edit/MkZcXJPS7hrcWh3M0MZ1?p=preview

I want to give a tooltip on mouse hover for every combination. The tooltip code that i have currently does like:

var tooltip = d3.select("body").append("div")  // tooltip code
   .attr("class", "tooltip")
   .style("opacity", 0);

 var circles = svg.selectAll(".dot")
      .data(data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 3.5)
      .attr("cx", function(d) { return x(d.petalWidth); })
      .attr("cy", function(d) { return y(d.petalLength); })
      .style("fill", function(d) { return color(d.species); })
      .on("mouseover", function(d) {
         tooltip.transition()
            .duration(200)
            .style("opacity", 1.0);
         tooltip.html(d.petalLength+", "+d.petalWidth)
            .style("left", (d3.event.pageX + 5) + "px")
            .style("top", (d3.event.pageY - 18) + "px");
      })
      .on("mouseout", function(d) {
         tooltip.transition()
            .duration(500)
            .style("opacity", 0);
      });

This will fail to return the correct tooltip for combinations other than petalWidth and d.petalLength.

Is there any way of knowing which combination has been selected and the associated numerical value for the combination?

Upvotes: 2

Views: 381

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

To do this:

First store the tool-tip info in a new variable(displayX/displayY) like this:

.attr("cx", function(d) {
          d.displayX = d.petalWidth;//so displayX holds the x info
          return x(d.petalWidth);

        })
        .attr("cy", function(d) {
          d.displayY = d.petalLength;//so displayY holds the y info
          return y(d.petalLength);
        })

When you set the combo reset the variables accordingly.

 svg.selectAll(".dot").transition().attr("cy", function(d) {
          d.displayY = d[yAxy];//reset the variable displayY
          return y(d[yAxy]);
        });

Same for

svg.selectAll(".dot").transition().attr("cx", function(d) {
  d.displayX = d[xAxy];//reset the variable displayX
  return x(d[xAxy]);
});

Now in the tool tip mouse hover use variable(displayX/displayY)

 .on("mouseover", function(d) {
          tooltip.transition()
            .duration(200)
            .style("opacity", 1.0);
          tooltip.html(d.displayY + ", " + d.displayX)//use displayX and displayY
            .style("left", (d3.event.pageX + 5) + "px")
            .style("top", (d3.event.pageY - 18) + "px");
        })
        .on("mouseout", function(d) {
          tooltip.transition()
            .duration(500)
            .style("opacity", 0);
        });

working code here

Hope this helps!

Upvotes: 1

Related Questions