我根据这样的对象数组绘制了一个条形图:
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}
]
我希望所有三个参数(第一个,第二个和第三个)都在我的条形图上的轴标签中,但“第一个”和“第二个”必须在第一行中,“第三个”必须在第二行中。我已经尝试使用wrap函数http://bl.ocks.org/mbostock/7555321,但它使用它们的长度包装标签,因为我需要用大量的单词包装它们
答案 0 :(得分:0)
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/