Search code examples
d3.jstooltip

how to add tooltip for rectangles in d3.js reading from json


I would like to create rectangles and have a tooltip for the same.

My json data is :

[
   [{ "a":10},{"b":11}],
   [{ "c":1},{"d":1}]
]

My code is :

var svggraph = d3.select("#graph").append("svg").attr("id","svggraph")
    .attr("width", 400)
    .attr("height", 300)
    .append("g")
    .attr("transform", "translate(50," + margin.top + ")");

var yvar = 20;
var x_axis = 1;

d3.json("Data.json", function(data) 
    {
        rectdata = data;

        for(x=0;x<rectdata.length;x++)
        {

          console.log(rectdata[x]);
          for (index=0;index<2; index++)
          {
            svggraph.append("rect")
                              .attr("x", setxaxis(index)) 
                              .attr("y", setyaxis(yvar))
                              .attr("width", 20)
                              .attr("height", 21)
                              .style("fill","white")    
                              .style("stroke","black");
                  svggraph.append("svg:title").text(function(d) { return "Tooltip"; });

          }

            yvar = yvar+21;
        }



    });



function setxaxis(x)
{


    if (x==4) return;

    if(x==0) 
    {
        return x_axis=0
    }
    else
    {
        x_axis=x_axis+25;
    }

    return x_axis; 

}
function setyaxis(y)
{

    return y; 


}

how to add tooltip like "a:10" or "b:11" on the 2X2 rectangle array created on the corresponding rectangles?


Solution

  • The easiest way to add a tooltip in SVG is to append a title element to the element you want to show a tooltip for (see e.g. this question).

    In your code, this would look something like this.

    svggraph.append("rect")
      // set attributes
      .append("title")
      .text(function(d) { return "Tooltip"; });