Accepted answer

If you're only looking to display the data elements when you mouseover the path/rect elements, you could try to add the titles directly onto those elements while they are being created?

For example:

var data = [0, 1, 2, 3, 4, 5],
    size = 300;

var canvas ="body")
                    .attr("width", size)
                    .attr("height", size);

var pixels = size / data.length;

      .attr("fill", "red")
      .attr("height", function(d){return d * pixels})
      .attr("width", pixels/2)
      .attr("x", function(d,i){return i * pixels})
      .attr("y", 0)
      .append("title")    //Adding the title element to the rectangles.
      .text(function(d){return d});

This code should create five rectangles with their data element present in a tooltip if you mouseover the rectangle.

Hope this helps.

Edit based on comment:

For a bottom to top graph, you can change the y attribute like so:

.attr("y", function(d){return size - d * pixels}) 

This addition will cause the bar to start at the difference between the maxHeight of your graph and the size of the bar, effectively turning a top-to-bottom graph into a bottom-to-top graph.


You can use d3js mouse event handler like this

var coordinates = [0, 0];
coordinates = d3.mouse(this);

var x = coordinates[0];
var y = coordinates[1];

It will provide you the current mouse coordinates.

Related Query

More Query from same tag