我正在尝试将换行应用于 d3 条形图中沿 x 轴的长变量标签。这是我在 Observable 笔记本中的图表:https ://observablehq.com/@unfpamaldives/figure4
我试图从这个块应用一个解决方案,主要包括以下内容:
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())
但这也不起作用(试图适应Bostock 的解决方案)。(我之前已经在其他 d3 可视化中使用了文本换行,这是值得的。)任何人都可以根据我的 Observable notebook的一个分支演示一个可行的解决方案吗?