Search code examples
reactjsd3.jsdonut-chart

How to add a tooltip to a pie chart?


I have implemented a react and d3 pie chart (https://observablehq.com/@stians/react-donut-chart-2), which I would like to add a div-based tooltip to with an absolute position and left and top px offset. What I am struggling with is to find the correct calculation for correctly positioning of the div within the center of a hovered path item. I do believe that arc.centroid(arcData) in the DonutChart component gives me the center line for the arc, but that is all coordinates within the svg.

Since the div would be outside of the svg, I would need to add positioning relative to the view port. I have attempted that by adding a useRef in the DonutContainer, and adding the ref to the figure (and then to use the ref.current.getBoundingClientRect()). This gives me access to values such as x,y, width, height of the figure tag. Could someone help me find the correct function for calculating left and top values for my tooltip which should be positioned in the center of the arc that is selected?


Solution

  • I've done this recently, you just need a little algebra to get it. Basically, because you get the centroid based on the svg ViewBox, you need to map that into the containind element. I've adapted what I did as it was slightly different, but the following function should help:

    
    const tooltipPos = (centroid) => {
    
        const svgBox = d3.select(`svg#<YOUR TAG>`).node().getBoundingClientRect();
       
        const posX = svgBox.x + (centroid[0] / width) * svgBox.width;
        const posY = svgBox.y + (centroid[1] / height) * svgBox.height;
    
        return [posX, posY];
    }
    
    

    Note that width and height are the ones passed onto the svg