Skip to content Skip to sidebar Skip to footer

How Can I Wrap Long Text Labels With D3.js?

I have created a node-tree using D3 and would like to understand how to wrap texts that are too long. nodeUpdate.select('text') .text(function(d) { if(d.name == 'ro

Solution 1:

The code from http://bl.ocks.org/mbostock/7555321 has two key parts.

The call to wrap() done

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
.selectAll(".tick text")
  .call(wrap, x.rangeBand());

which is expecting a text element and a width like done in

node.append("text")
  // Make sure to have a text element
  .text(function(d) {
    return d.name;
  })
  .call(wrap, 50);

The confusing part here is that call statements apply to the current selection like .tick text or all nodes.

The second part is the required text.text() otherwise it does not work.

functionwrap(text, width) {
  text.each(function() {
  var text = d3.select(this),
      words = text.text().split(/\s+/).reverse(),

Post a Comment for "How Can I Wrap Long Text Labels With D3.js?"