Skip to content

Instantly share code, notes, and snippets.

@jml6m
Forked from mbostock/.block
Last active September 25, 2023 08:55
Show Gist options
  • Save jml6m/02b06ffc269982fa987f to your computer and use it in GitHub Desktop.
Save jml6m/02b06ffc269982fa987f 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);
}
}
});
}
@praveenuics
Copy link

praveenuics commented Oct 22, 2017

Could you please direct me to the link where i can find the above code in typescript? i am working with d3 v4 in angular2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment