Nupur
Nupur

Reputation: 163

How to word wrap legend labels in d3

I am using an aster plot of d3,with legend labels around the arc.

A working example here.

var text = arcs.append("svg:text")
.attr("transform", function(d) {
    d.outerRadius = outerRadius + 75;
    d.innerRadius = outerRadius + 70;
    return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle") //center the text on it's origin
.style("fill", "black")
.style("font", "bold 12px Arial")
.text(function(d, i) { return dataSet[i].legendLabel; }) // <- split this into multiple lines?

But i want to break the long label in new lines, how can i achieve it?

Thanks

Upvotes: 2

Views: 3472

Answers (1)

Nikos
Nikos

Reputation: 3297

You could add a wrap function for each of your text elements. I am not sure that it will be your best option, but it will be a start.

Your wrap function just splits the label by the space character. You can add a regular expression for more flexibility.

function wordwrap(text) {
  var lines=text.split(" ")
  return lines
}

Then, for each of your text elements, instead of just adding the text attribute, you could loop for each wrapped part of the text.

var text = arcs.append("svg:text")
        .attr("transform", function(d) {
            d.outerRadius = outerRadius + 75;
            d.innerRadius = outerRadius + 70;
            return "translate(" + arc.centroid(d) + ")";
        })
        .attr("text-anchor", "middle") //center the text on it's origin
        .style("fill", "black")
        .style("font", "bold 12px Arial")
        .each(function (d, i) {
          var lines = wordwrap(dataSet[i].legendLabel)
          for (var i = 0; i < lines.length; i++) {
            d3.select(this).append("tspan")
                .attr("dy",13)
                .attr("x",function(d) { 
                   return d.children1 || d._children1 ? -10 : 10; })
                  .text(lines[i])
          }
        })

You will need to remove your line:

.text(function(d, i) { return dataSet[i].legendLabel; })

as this will not be applicable any more.

The result is here:

image

Not very pretty, but perhaps closer to what you want to achieve.

Hope this helps

Upvotes: 2

Related Questions