[英]adding text to a circle in d3
I cant seem to find a way to add the strings from the data to my circles.. the code that refers to the text isn't working, and isn't making errors too.. any ideas? 我似乎找不到一种将数据中的字符串添加到我的圈子中的方法..引用文本的代码不起作用,也不会出错..有什么想法吗? thank you very much :)
非常感谢你 :)
//Create circles
var circle=svg.append("g")
.attr("class", "circles")
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", w / 2)
.attr("cy", h / 2)
.attr("r", 4)
.transition()
.duration(2000)
.attr("cx", function(d) {
return xScale(d.accountancy);
})
.attr("cy", function(d) {
return yScale(d.income);
})
.transition()
.duration(2000)
.attr("r", function(d) {
return d.income/radiusOffset;
})
.attr("fill",function(d){
if(d.accountancy<0){
return "#DD2626";
}
return "#4CA64C";
});
//create text
var text=svg.append("g").selectAll("text")
.data(data)
.enter()
.append("text")
.attr("x", function(d) {
return xScale(d.accountancy);
})
.attr("y",function(d) {
return xScale(d.income);
})
.attr("font-size","15px")
//Create X axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (h - padding + 5) + ")")
.call(xAxis);
//Create Y axis
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + (padding - 5) + ",0)")
.call(yAxis);
</script>
</body>
You need to create a <g>
element per circle, which will include both your <circle>
and your <text>
elements. 您需要为每个圆圈创建一个
<g>
元素,其中将同时包含您的<circle>
和<text>
元素。 For example: 例如:
//Creating the groups
var circles = svg.selectAll("g.circles");
//Adding circles to the groups
circles = circles.data(data)
.enter()
.append("g")
.classed("circles", true);
circles.append("svg:circle")
//Styling the circles.
circles.selectAll("circle")
.attr("cx", w / 2)
.attr("cy", h / 2)
.attr("r", 4);
//Adding text labels to the groups
circles.append("text");
//Styling text
circles.selectAll("text")
.text("Put your text stuff here")
.attr("font-family", "Courier")
.attr("fill", "black")
.style("opacity", "0.8")
.attr("font-size", "0.8em")
.attr("text-anchor", "middle");
There's probably more elegant/concise ways to do this, but this has worked for me in the past. 可能有更优雅/简洁的方法可以执行此操作,但这在过去对我有用。 See also this example by Mike Bostock .
另请参见Mike Bostock的此示例 。
.attr("y",function(d) { return xScale(d.income); .attr(“ y”,function(d){return xScale(d.income);
the problem was here.. i used the xScale for the y axe as well ... changed to: 问题在这里..我也将xScale用作y斧头...更改为:
.attr("y",function(d) { return yScale(d.income); .attr(“ y”,function(d){return yScale(d.income);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.