Sunburst Diagram Intelligent Text Wrapping

2.2k Views Asked by At

I have a zoomable sunburst diagram based on the great d3 "coffee wheel" example:

enter image description here

In that example there is simple text wrapping code that searches for a space in a label and wraps the text at the first space character:

var textEnter = text.enter().append("text")
  .style("fill-opacity", 1)
  .style("fill", function(d) {
      return brightness(d3.rgb(colour(d))) < 125 ? "#eee" : "#000";
  })
  .attr("text-anchor", function(d) {
      return x(d.x + d.dx / 2) > Math.PI ? "end" : "start";
  })
  .attr("dy", ".2em")
  .attr("transform", function(d) {
      var multiline = (d.name || "").split(" ").length > 1,
      angle = x(d.x + d.dx / 2) * 180 / Math.PI - 90,
      rotate = angle + (multiline ? -.5 : 0);
      return "rotate(" + rotate + ")translate(" + (y(d.y) + padding) +
              ")rotate(" + (angle > 90 ? -180 : 0) + ")";
      })
  .on("click", click);

textEnter.append("tspan")
  .attr("x", 0)
  .text(function(d) {
      return d.depth ? d.name.split(" ")[0] : "";
  });

textEnter.append("tspan")
  .attr("x", 0)
  .attr("dy", "1em")
  .text(function(d) {
      return d.depth ? d.name.split(" ")[1] || "" : "";
  });

This code works fine, but it is very basic, especially if the whole label would have fitted on one line in the available sunbust segment (eiether because the particular label is short or the available space is large enough as the sunburst is zoom'ed). In densely packed sunbursts wrapping the labels unnecesarily causes the diagram to look messy/cluttered.

  1. I would like to make the text processing more intelligent and compare the length of the label with the available space (noting that the "width" of a segment changes depending on the depth of segments visible when zoom'ed).

  2. Also if the available space for the label is known then the text wrapping could be more intelligent eg if the label contains more than two words code can decide whether it is better to break at first space or second.

If anyone has already solved this problem and has some example, greatly appreciated if it can be shared. Alternatively if anyone has any ideas about how the length of a label can be compared to the changing available space?

0

There are 0 best solutions below