答案可能会迟到,但希望对您有所帮助。我在问题中使用了Mike Bostock’s Wrapping long labels 示例。
这是我对您的代码所做的不同之处。
为图表添加边距以使其美观:
var chart = nv.models.multiBarHorizontalChart().margin({
top: 30, right: 20, bottom: 50, left: 100
});
最后,我选择了图表上的所有xAxis 刻度并将Mike Bostock’s Wrapping long labels function wrap 应用到它。
d3.selectAll(".nv-x.nv-axis .tick text").each(function(i, e) {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word, line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
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(" "));
// TDOD : Make 80 a dynamic value based on the bar width/height
if (tspan.node().getComputedTextLength() > 80) {
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);
}
}
});
最终输出
Here's 示例的工作版本。