whytheq whytheq - 28 days ago 4
Javascript Question

How to add text to paths

I suspect I'm barking up the wrong tree - although I've got no errors in the console to help me out.

I've got this block of code:

var path = svg.data([json]).selectAll("path")
.data(partition.nodes)
.enter()
.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).name);
})
.attr("fill-rule", "evenodd")
.style("opacity", 1)
.each(stash);

//>>this section functions ok
path.append("title")
.text(function(d) {
return d.name + ": " + d.amount;
});

//>>this section throws no errors but "foo" does not appear
path.append("text")
.text(function(d) {
return "foo";
})
.style("stroke", "#3b5998")
.style("fill", "#3b5998");


The code snippet beginning
path.append("title")...
works ok but the final snippet beginning
path.append("text")...
adds the text foo to the html but it is not visible on the webpage - why is it not visible and how do I add labels?

This is part of this visual:

http://plnkr.co/edit/q9ODd5?p=preview

Answer

text cannot be nested with a path. You'll need to add it to the svg instead. Additionally, you'll want to position the text in some way:

  svg.append("text")
    .text(function(d) {
        return "foo";
    })
    .attr("x", function(){ return 0 })
    .attr("y", function(){ return 0 })
    .style("stroke", "#3b5998")
    .style("fill", "#3b5998");