javascript d3.js:如何为图表上的散点添加标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12266967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
d3.js: How to add labels to scatter points on graph
提问by tmnt-rafael
I am trying to add labels to the scatter points on this graph: http://bost.ocks.org/mike/d3/workshop/dot-chart.html
我正在尝试为该图的散点添加标签:http: //bost.ocks.org/mike/d3/workshop/dot-chart.html
I thought that modifying this code a little bit would work, but it didn't:
我认为稍微修改此代码会起作用,但它没有:
svg.selectAll(".dot")
.append("text")
.text("fooLabelsOfScatterPoints");
回答by tmnt-rafael
Mike Robinson, your example helped.
迈克罗宾逊,你的例子有帮助。
For those who are wondering, here is what I did:
对于那些想知道的人,这是我所做的:
I removed:
我删除了:
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
.attr("r", 12);
and added:
并补充说:
var node = svg.selectAll("g")
.data(data)
.enter()
.append("g");
node.append("circle")
.attr("class", "dot")
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
.attr("r", 12);
node.append("text")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return y(d.y); })
.text("fooLabelsOfScatterPoints");
I appended "text" tags onto "g" tags, as opposed to appending "text" tags onto "circle" tags.
我将“text”标签附加到“g”标签上,而不是将“text”标签附加到“circle”标签上。
回答by ezchx
When I tried the node solution, some of my data disappeared (?), so I just added a new class called "dodo" which worked for me:
当我尝试节点解决方案时,我的一些数据消失了(?),所以我添加了一个名为“dodo”的新类,它对我有用:
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) { return x(d.time); })
.attr("cy", function(d) { return y(d.place); })
.style("fill", function(d) { return color(d.species); });
svg.selectAll(".dodo")
.data(data)
.enter().append("text")
.attr("class", "dodo")
.attr("x", function(d) { return x(d.time); })
.attr("y", function(d) { return y(d.place); })
.attr("dx", ".71em")
.attr("dy", ".35em")
.text(function(d) { return d.name;});