如何将文本添加到路径
问题描述:
我怀疑我在咆哮错误的树 - 虽然我没有在控制台中的错误来帮助我。如何将文本添加到路径
我有这段代码:
var path = svg.data([json]).selectAll("path")
.data(partition.nodes)
.enter()
.append("path")
.attr("display", function(d) {
return d.depth ? null : "none";
})
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) {
return color((d.children ? d : d.parent).name);
})
.attr("fill-rule", "evenodd")
.style("opacity", 1)
.each(stash);
//>>this section functions ok
path.append("title")
.text(function(d) {
return d.name + ": " + d.amount;
});
//>>this section throws no errors but "foo" does not appear
path.append("text")
.text(function(d) {
return "foo";
})
.style("stroke", "#3b5998")
.style("fill", "#3b5998");
开始path.append("title")...
代码段工程确定,但开始path.append("text")...
最后片段添加文本FOO到HTML,但它不是网页上可见的 - 为什么它不可见,我如何添加标签?
这是此视觉的一部分:
答
text
不能嵌套用path
。您需要将其添加到svg
。此外,你要以某种方式定位文本:
svg.append("text")
.text(function(d) {
return "foo";
})
.attr("x", function(){ return 0 })
.attr("y", function(){ return 0 })
.style("stroke", "#3b5998")
.style("fill", "#3b5998");
+0
感谢您的帮助 - 我添加了下面的代码,将标签分发到每个弧 – whytheq
答
工作结束代码如下所示:
var path = svg.data([json]).selectAll(".theArc")
.data(partition.nodes)
.enter()
.append("path")
.attr("class", "theArc") //<<<<<<<<<<new
.attr("id", function(d,i) { return "theArc_"+i; }) //Give each slice a unique ID //<<<<<<<<<<new jq
.attr("display", function(d) {
return d.depth ? null : "none";
})
.attr("d", arc)
.style("stroke", "#fff")
.style("fill", function(d) {
return color((d.children ? d : d.parent).name);
})
.attr("fill-rule", "evenodd")
.style("opacity", 1)
.each(stash);
path
.append("title") //mouseover title showing the figures
.text(function(d) {
return d.name + ": " + d.amount;
});
svg.data([json]).selectAll(".theTxts")
.data(partition.nodes)
.enter()
.append("text")
.attr("class", "theTxts")
.attr("dx", 10) //Move the text from the start angle of the arc
.attr("dy", 18) //Move the text down
.append("textPath")
.attr("xlink:href", function(d, i) {
return "#theArc_" + i;
})
.text(function(d) {
return d.name;
})
.style("stroke", "#3b5998")
.style("fill", "#3b5998");
对于真正深入教程涵盖所有这一切,你可能希望有看看[*“使用D3.js在弧上放置文本”*](http://www.visualcinnamon.com/2015/09/placing-text-on-arcs.html)。这是值得的时间! – altocumulus
@altocumulus伟大的链接 - 谢谢....看! http://run.plnkr.co/plunks/V4Zr16/ – whytheq