How to wrap d3.js labels with ticks?

Member

by adan , in category: Javascript , 4 months ago

How to wrap d3.js labels with ticks?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 4 months ago

@adan 

To wrap d3.js labels with ticks, you can use the following code:

  1. Create a function to wrap the labels:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        x = text.attr("x"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");

    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}


  1. Use the function to wrap the labels:
1
2
3
// Select the tick labels
svg.selectAll(".tick text")
  .call(wrap, 100); // 100 is the width at which to wrap the labels


In this code snippet, the wrap function takes the text element and a width parameter as inputs. It splits the text into words, calculates their length, and wraps the text within the specified width. Finally, the wrap function is called on the tick labels using the specified width value to wrap the labels.