How to do wordwrap for chart labels using d3.js

后端 未结 5 463
灰色年华
灰色年华 2020-12-15 23:41

I am trying to implement the horizontal bar chart using d3.js.Some of the chart labels are too long. How to do word wrap for the chart labels on y aixs?

Source code:

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 00:30

    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 = d3.select(t);
        var p = d3.select(t.parentNode);
        p.append("foreignObject")
            .attr('x', -width/2)
            .attr("width", width)
            .attr("height", 200)
          .append("xhtml:p")
            .attr('style','word-wrap: break-word; text-align:center;')
            .html(d);    
    
        el.remove();
    
    };
    

    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:

    d3.select('#xaxis')
        .selectAll('text')
            .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).

    Resulting image with wrapped labels

提交回复
热议问题