Multiline axis of svg text in d3

I am trying to make a simple histogram with a label for each bar when the axis points to the x axis. Longer shortcuts move one above the other. Since svg text elements do not support word wrap, I was looking for alternative solutions.

Changing the category text that goes into labels to include the correct <tspan> elements do not work, because the text is not set as innerHtml, but rather as the source text of the element. I also looked at post-processing shortcuts to remove text and replace it with tspans, but I have not yet found an elegant way to do this.

Unfortunately, I cannot use foreignObject, since I need IE9 support, but many of the same problems with markup replacement will in any case be applied to this solution.

Has anyone solved this problem in the past or had any suggestions?

+8
svg
source share
1 answer

You can do the wrapping manually, as in this example by Mike Bostock:

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"), dy = parseFloat(text.attr("dy")), tspan = text.text(null).append("tspan").attr("x", 0).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", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word); } } }); } vis.selectAll(".tick text") .call(wrap, 100); 
+5
source share

All Articles