我正在尝试将换行应用于 d3 条形图中沿 x 轴的长变量标签。这是我在 Observable 笔记本中的图表:https://observablehq.com/@unfpamaldives/figure4
我尝试应用解决方案 from this block ,主要包括以下内容:
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)
}
}
})
}
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${height})`)
.call(xAxis)
.selectAll(".tick text")
.call(wrap, x.bandwidth())
它看起来像什么:
我想要实现的目标:
我还尝试将 wrap
函数移动到代码中的其他位置(之前和之后),并尝试移动以下几行
.selectAll(".tick text")
.call(wrap, x.bandwidth())
从该代码块中的某个位置开始工作,如下所示:
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.style("font-family", "HelveticaNeueLTStd-Cn")
.style("font-size", "9px")
.call(d3.axisBottom(x).tickSizeOuter(0))
.selectAll(".tick text")
.call(wrap, x.bandwidth())
但是this too (尝试适应 Bostock's solution )不起作用。 (我之前已经在其他 d3 可视化中使用了文本换行,这是值得的。)任何人都可以演示基于 my Observable notebook 分支的工作解决方案吗? ?
最佳答案
我成功地对 this example 中的 x 轴条/变量标签应用了文本换行技术。来自Gerardo Furtado 。它需要以下代码:
svg.append("g")
.call(yAxis);
const axis = svg.append("g")
.call(xAxis);
setTimeout(()=>{
axis.selectAll(".tick text")
.style("font-family", "HelveticaNeueLTStd-Cn")
.style("font-size", "9px")
.call(wrap, x.bandwidth());
}, 0);
这是working solution .
关于javascript - 勾选文本/变量标签未在 d3 条形图中换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60421252/