Skip to content

Instantly share code, notes, and snippets.

@nobitagit
Forked from jml6m/README.md
Created May 12, 2017 13:51
Show Gist options
  • Save nobitagit/373b94ea330f3ceeb3582a92ef246baa to your computer and use it in GitHub Desktop.
Save nobitagit/373b94ea330f3ceeb3582a92ef246baa to your computer and use it in GitHub Desktop.

This example, using satirical data from The Onion, demonstrates how to wrap long axis labels to fit on multiple lines.

UPDATE: In order to make this code work for horizontal bar charts, the code for setting the 'y' attribute must be used when setting the 'x' attribute. I've included only the wrap function in this fork.

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);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment