'D3.js display chart segment data on click
First time posting so please bear with me. I'm playing around with D3.js and charts at the moment and having trouble getting a working onclick function to display the selected arc's data in a div (id="showData"). I've tried attaching onclick to the arc generator using .on(click){function(d, I) const MyData = ["datapoint"]} but I'm not sure if this is the right spot or of how to lift specific datapoints from the selected segment so it's probably wrong.
function drawSunburst(data) {
// Find the root node, calculate the node.value, and sort our nodes by node.value
root = d3.hierarchy(data)
.sum(function (d) { return d.size; })
.sort(function (a, b) { return b.value - a.value; });
// Calculate the size of each arc; save the initial angles for tweening.
partition(root);
arc = d3.arc()
.startAngle(function (d) { d.x0s = d.x0; return d.x0; })
.endAngle(function (d) { d.x1s = d.x1; return d.x1; })
.innerRadius(function (d) { return d.y0; })
.outerRadius(function (d) { return d.y1; })
// Add a <g> element for each node; create the slice variable since we'll refer to this selection many times
slice = g.selectAll('g.node').data(root.descendants(), function(d) { return d.data.name; }); // .enter().append('g').attr("class", "node");
newSlice = slice.enter().append('g').attr("class", "node").merge(slice);
slice.exit().remove();
// Append <path> elements and draw lines based on the arc calculations. Last, color the lines and the slices.
slice.selectAll('path').remove();
newSlice.append('path').attr("display", function (d) { return d.depth ? null : "none"; })
.attr("d", arc)
.style('stroke', '#fff')
.style("fill", function (d) { return color((d.children ? d : d.parent).data.name); });
// Populate the <text> elements with our data-driven titles.
slice.selectAll('text').remove();
newSlice.on("click", highlightSelectedSlice);
};
d3.selectAll(".showSelect").on("click", showTopTopics)
d3.selectAll(".sizeSelect").on("click", sliceSizer);
// Redraw the Sunburst Based on User Input
function highlightSelectedSlice(c,i) {
clicked = c;
var rootPath = clicked.path(root).reverse();
rootPath.shift(); // remove root node from the array
newSlice.style("opacity", 0.4);
newSlice.filter(function(d) {
if (d === clicked && d.prevClicked) {
d.prevClicked = false;
newSlice.style("opacity", 1);
return true;
} else if (d === clicked) {
d.prevClicked = true;
return true;
} else {
d.prevClicked = false;
return (rootPath.indexOf(d) >= 0);
}
})
.style("opacity", 1);
// var ThisData = d3.select(this)
// var ThisDatum = ThisData.datum()["data"]
// return showData
// .html(
// ThisDatum["size"]
// )
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
