klonitklonit
klonitklonit

Reputation: 319

Adding label to D3 path

I know how to add text element to simple node (append text). The problem is when I would like to add text to path surrounding several nodes. I have created example on http://jsfiddle.net/FEM3e/5/ Please ignore nodes in upper left corner. So I have two groups of nodes. And I would like to add text for each group. Printscreen of desired output http://dopisna.bencin.si/screenshot.png.

I set path in

force.on("tick", function () {
        node.attr("transform", function (d) {
            return "translate(" + d.x + "," + d.y + ")";
        });
        vis.selectAll("path")
            .data(groups)
            .attr("d", singlePath)
            .enter().insert("path", "g")
            .style("fill", groupFill)
            .style("stroke", groupFill)
            .style("stroke-width", 57)
            .style("stroke-linejoin", "round")
            .style("opacity", .7);
    });

I have tried appending text with no success. I am asking for some hints.

Upvotes: 3

Views: 7587

Answers (1)

user1614080
user1614080

Reputation: 2874

OK then. The problem is that you're using text instead of textPath. I've modified your fiddle and now there's some text, albeit some rather ugly text, appended to your path.

The only real change I've made is the addition of this snippet:

        vis.selectAll("text")
            .data(groups)
            .enter()
        .append("text")
            .attr("x", 8)
            .attr("dy", 28)
           .append("textPath")
        .attr("xlink:href", function (d,i) { return "#path_" + i; })
        .text(function (d,i) { return "path_" + i; });

You can see that you go through the usual selection and data binding. You then append your text with the attributes you want (definitely change the ones I borrowed from Mikes Bl.ock) and then you append the text path linking it to a path element in the xlink:href attribute. Obviously you then create some text. One of the cool things about textPath is that it allows you append curved paths.

I think that there's a bit of overkill using the groups as data for the textPath, so you might want to select a more appropriate data selection to bind to this.

Upvotes: 2

Related Questions