Skip to content

Instantly share code, notes, and snippets.

@jml6m jml6m/README.md forked from mbostock/.block
Last active Oct 22, 2017

Embed
What would you like to do?

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

This comment has been minimized.

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
You can’t perform that action at this time.