繁体   English   中英

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

[英]How to add a line break using d3.js text

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

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/ 之类的东西并设置适当的bgPadding属性; 这涉及设置一个新数组,自定义其相关属性以匹配您的基础数据,以及格式化注释外观。

否则(可能是一个比在不需要其他功能的情况下跳入 d3-annotation 更简单的解决方案)您可以 append 为每个单元格添加一个额外的文本元素,因此一个元素显示数据名称,另一个显示项目计数。 其中第二个将从初始值 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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM