jenswirf
jenswirf

Reputation: 7317

How to add single label per svg element?

I'm attempting to add a simple data label to this example

svg.selectAll("text")
        .data(data)
        .enter()
        .append("text")
        .attr("text-anchor", "middle")
        .attr("fill", "red")
        .text(function(d) { return d[0] });

but it writes all the data in all labels which I think is because the graph is split over several individual svg-elements. How can I fix this?

Fiddle

Upvotes: 0

Views: 4365

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

You're already binding the data to the SVGs, so there's no need for you to bind it again to the text elements. svg is actually the selection of SVGs here, so all you have to do is

svg.append("text")
        .attr("text-anchor", "middle")
        .attr("fill", "red")
        .text(function(d) { return d[0] });

Complete example here.

Upvotes: 2

Related Questions