如何在轴标签中只包装一个单词

How to wrap only one word in axis labels

本文关键字:单词 一个 包装 标签      更新时间:2023-09-26

我画了一个基于对象数组的柱状图,如下图所示:

var arr = [
{first: "a", second: "middle1", third: "firstVeryVeryVeryVeryLong", value: 20},
{first: "secondVeryVeryVeryVeryLong", second: "b", third: "middle2", value: 40},
{first: "middle3", second: "thirdVeryVeryVeryVeryLong", third: "c", value: 51}
]

我希望所有三个参数(first, second和third)都在我的条形图上的轴标签中,但是"first"answers"second"必须在第一行,"third"必须在第二行。我曾尝试使用换行函数http://bl.ocks.org/mbostock/7555321,但它使用长度来换行标签,因为我需要按字数

进行换行。

这是我的小提琴:https://jsfiddle.net/anton9ov/pqhuuk12/

可采用https://bl.ocks.org/mbostock/7555321中的wrap函数:

svg.append("g")
        .attr("transform", "translate(" + labelLength + ", 0)")
        .call(yAxis)
        .selectAll('text')
        .call(wrap, yScale.bandwidth());
function wrap(text, height) {
    text.each(function() {
        var text = d3.select(this),
                words = text.text().split(/'s+/).reverse(),
                word,
                line = [],
                lineNumber = 0,
                lineHeight = 1.1, // ems
                 //start the text from bar top
                y = text.attr("y") - (barHeight/2), 
                dy = parseFloat(text.attr("dy")),
                tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
        while (word = words.pop()) {
            line.push(word);
            tspan.text(line.join(" "));
            if (tspan.node().getComputedTextLength() > height) {
                line.pop();
                tspan.text(line.join(" "));
                line = [word];
                tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
            }
        }
    });
}

这是你更新的小提琴:https://jsfiddle.net/pqhuuk12/8/

相关文章: