@jerad
To add tooltips for each section of a donut chart in a loop using d3.js, you can do the following:
1
|
<div id="tooltip" style="display: none;"></div> |
1 2 3 4 5 6 7 8 9 10 11 12 |
var tooltip = d3.select("#tooltip"); function showTooltip(text, event) { tooltip.html(text) .style("left", (event.pageX) + "px") .style("top", (event.pageY - 28) + "px") .style("display", "block"); } function hideTooltip() { tooltip.style("display", "none"); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
var data = [ { label: "A", value: 30 }, { label: "B", value: 20 }, { label: "C", value: 50 } ]; var width = 400; var height = 400; var radius = Math.min(width, height) / 2; var color = d3.scaleOrdinal(d3.schemeCategory10); var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); var arc = d3.arc() .innerRadius(100) .outerRadius(radius); var pie = d3.pie() .value(function(d) { return d.value; }); var arcs = svg.selectAll("g.arc") .data(pie(data)) .enter() .append("g") .attr("class", "arc"); arcs.append("path") .attr("d", arc) .attr("fill", function(d, i) { return color(i); }) .on("mouseover", function(d, i) { showTooltip(data[i].label + ": " + data[i].value + "%", d3.event); }) .on("mouseout", hideTooltip); |
With this code, each section of the donut chart will display a tooltip with the label and value of the corresponding data point when the mouse is over the section, and hide the tooltip when the mouse moves away. You can customize the tooltip appearance and content as needed.