如何使用d3.js文本添加换行符



我正在尝试将文本添加到我正在创建的树图中,我希望它像一样

Test name
Item Count: 402

但是它打印

Test name Item Count: 402

我的代码是这个

cells.append("text")
.attr("x", d => x(d.x0 + 5) )
.attr("y", d => y(d.y0 + 20) )
.style("font", "13px sans-serif")
.text(d => d.data.name + "  n Item Count: " + d.data.itemCount)
.attr("fill", "black")

感谢您的帮助

不幸的是,这在原生d3中是不可能的,因为您的换行符在svg中无法识别。

要自动设置这样的内容,您必须使用以下内容https://d3-annotation.susielu.com/并设置适当的CCD_ 1属性;这包括设置一个新数组,自定义其相关属性以匹配基础数据,以及格式化注释外观。

否则(这可能是一个比在不需要其他功能的情况下跳转到d3注释简单得多的解决方案(,您可以为每个单元格附加一个额外的文本元素,从而使一个元素显示数据名称,另一个显示项计数。其中的第二个将从初始值20偏移一定的数字(在下面的例子中,我只是简单地添加了10px(:

cells.append("text")
.attr("x", d => x(d.x0 + 5) )
.attr("y", d => y(d.y0 + 20) )
.style("font", "13px sans-serif")
.text(d => d.data.name )
.attr("fill", "black")

cells.append("text")
.attr("x", d => x(d.x0 + 5) )
.attr("y", d => y(d.y0 + 30) ) //note each of these is 10px lower
.style("font", "13px sans-serif")
.text(d => Item Count: " + d.data.itemCount)
.attr("fill", "black")

最新更新