Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to do wordwrap for chart labels using d3.js

Here is a working implementation I’ve written by pulling together various bits. As the other answer suggests, Foreignobject is still the way to go. First the function:

var insertLinebreaks = function (t, d, width) {
    var el =;
    var p =;
        .attr('x', -width/2)
        .attr("width", width)
        .attr("height", 200)
        .attr('style','word-wrap: break-word; text-align:center;')



This takes in a text Element (t), the text content (d), and the width to wrap to. It then gets the parentNode of the text object, and attaches a foreignObject node to it into which an xhtml:p is added. The foreignObject is set to the desired width and offset -width/2 to center. Finally, the original text element is deleted.

This can then be applied to your axis elements as follows:'#xaxis')
        .each(function(d,i){ insertLinebreaks(this, d, x1.rangeBand()*2 ); });

Here I’ve used rangeBand to get the width (with *2 for 2 bars on the graph).

This post first appeared on Martin Fitzpatrick – Python Coder, Postgraduate, please read the originial post: here

Share the post

How to do wordwrap for chart labels using d3.js


Subscribe to Martin Fitzpatrick – Python Coder, Postgraduate

Get updates delivered right to your inbox!

Thank you for your subscription