包装文本标签 [英] Wrapping text labels
本文介绍了包装文本标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前正尝试在图表上包装一些文字标签。我按照Mike Bostock的示例在这里。当我尝试实现他的例子,它适用于我的Y轴,但我需要它在我的X轴上工作,我不知道为什么它不工作。
Currently trying to wrap some text labels on my graph. I'm following Mike Bostock's example here. When I tried implementing his example it works for my y-axis but I need it to work on my x-axis and I'm not exactly sure why it's not working.
chart2.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Potential Years Lost")
.call(wrap, x0.rangeBand());
function wrap(text, width) {
text.each(function() {
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(" "));
if (tspan.node().getComputedTextLength() > width) {
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);
}
}
});
}
function type(d) {
d.value = +d.value;
return d;
}
这是我的小提琴: http://jsfiddle.net/flyingburrito/0xq0qc42/1/
推荐答案
小改变,你实际上没有在x轴刻度线上调用 wrap
(你只是为y轴标签调用它) 。
Small change, you weren't actually calling wrap
on the x-axis tick text (you were only calling it for the y-axis label).
您需要将最后两行添加到此x轴所在的块中
You needed to add the final two lines to this block where the x-axis is appended
//draw the bars
chart2.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll(".tick text")
.call(wrap, x0.rangeBand());
在这里工作: http://jsfiddle.net/henbox/v5fj0263/
这篇关于包装文本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文