Reputation: 8178
I have the following code:
svg
.selectAll('mySlices')
.data(data_ready)
.enter()
.append('path')
.attr('d', arcGenerator)
.attr('fill', function(d){ return(color(d.data.key)) })
.attr("stroke", "black")
.style("stroke-width", "2px")
.style("opacity", 0.7)
And I'd like to append text elements right after each of my path elements.
This doesn't seem to work:
svg
.selectAll('mySlices')
.data(data_ready)
.enter()
.append('path')
.attr('d', arcGenerator)
.attr('fill', function(d){ return(color(d.data.key)) })
.attr("stroke", "black")
.style("stroke-width", "2px")
.style("opacity", 0.7)
.append('text')
.attr('class', 'label')
.text(function(d){ return d.data.key})
.attr("transform", function(d) { return "translate(" + arcGenerator.centroid(d) + ")"; })
.style("text-anchor", "middle")
.style("font-size", 10)
What's important to me is that each text element immediately follow the respective path element in the document so I can use the + CSS Sibling selector to show text on hover of the path element.
I'm open to alternatives, but can't think of any.
Ultimately I just want to display the text on hover for each pie segment.
Upvotes: 0
Views: 218
Reputation: 1959
Hi you can keep track of the selection storing it as a variable. The difference is that d3 working chaining and applying functions. You also need to add the class name for your selection, in case you want to select them.
const slices = svg
.selectAll('.mySlices')
.data(data_ready)
.enter()
.append('path')
.attr('d', arcGenerator)
.attr('fill', function(d){ return(color(d.data.key)) })
.attr("stroke", "black")
.style("stroke-width", "2px")
.style("opacity", 0.7)
.attr("class", "mySlices");
slices.append('text')
.attr('class', 'label')
.text(function(d){ return d.data.key})
.attr("transform", function(d) { return "translate(" + arcGenerator.centroid(d) + ")"; })
.style("text-anchor", "middle")
.style("font-size", 10);
Upvotes: 1