Skip to content

Instantly share code, notes, and snippets.

Forked from mbostock/.block
Last active October 22, 2017 18:01
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 =,
words = text.text().split(/\s+/).reverse(),
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()) {
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
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