简体   繁体   English

如何在饼图中添加工具提示?

[英]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.我已经实现了一个 react 和 d3 饼图( https://observablehq.com/@stians/react-donut-chart-2 ),我想向其中添加一个基于 div 的工具提示,具有绝对位置和左侧和顶部像素偏移。 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.我正在努力寻找正确的计算方法,以便在悬停的路径项的中心内正确定位 div。 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.我确实相信 DonutChart 组件中的 arc.centroid(arcData) 为我提供了弧的中心线,但这是 svg 中的所有坐标。

Since the div would be outside of the svg, I would need to add positioning relative to the view port.由于 div 将在 svg 之外,因此我需要添加相对于视口的定位。 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()).我已经尝试通过在 DonutContainer 中添加一个 useRef,并将 ref 添加到图中(然后使用 ref.current.getBoundingClientRect())。 This gives me access to values such as x,y, width, height of the figure tag.这使我可以访问图形标记的 x、y、宽度、高度等值。 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?有人可以帮我找到正确的函数来计算我的工具提示的左值和上值,它应该位于所选弧的中心吗?

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.基本上,因为您根据 svg ViewBox 获得质心,所以您需要将其映射到 containsind 元素。 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请注意,宽度和高度是传递到 svg 的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM