Adding Text To D3 Circle
Solution 1:
Another option, close to @cyril's is to use a g
element and place both the circle and text inside. This saves you the double data-bind and double movement update:
var nodes = svg.selectAll("g")
.data(data);
var g = nodes.enter().append("g")
g.append("circle")
.attr("class", function(d) {
return d.ratingCategory;
})
.attr("r", 2)
.attr("id", function(d){return d.objectName;})
.on("mouseover", function(d) {
showPopover.call(this, d);
})
.on("mouseout", function(d) {
removePopovers();
});
g.append("text")
.attr("dx",12)
.attr("dy",".35em")
.text(function(d){
return d.objectName;
});
And update the node position in the tick function as:
nodes.each(collide(.2))
.attr("transform", function(d){ //<-- use transform it's not a greturn"translate(" + d.x + "," + d.y + ")";
});
Updated block.
Solution 2:
Problem 1:
You are making the text within the circle dom, which is not correct.
<circle class="Low" cx="521.4462169807987" cy="183.39012004057906" r="10" id="171" data-original-title="" title="" aria-describedby="popover833687"><text dx="12" dy=".35em">171</text></circle>
It should have been this way:
<circle class="ratingCategory1" cx="343.02601945806816" cy="333.91072717787176" r="10" id="9" data-original-title="" title="" aria-describedby="popover766707"></circle>
<text x="317.17351217946583" y="310.10556778212015" dx="12" dy=".35em" class="All-Objects">4</text>
How to do this:
nodes.enter().append("circle") //make circle//.attr("class", "node")
.attr("class", function(d) {
return d.ratingCategory;
})
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
.attr("r", 2)
.attr("id", function(d){return d.objectName;})
.on("mouseover", function(d) {
showPopover.call(this, d);
})
.on("mouseout", function(d) {
removePopovers();
})
;
var text = svg.selectAll("text")
.data(data).enter().append("text")
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y;
})
.attr("dx",12)
.attr("dy",".35em")
.text(function(d){
return d.objectName;
});
Problem 2
Inside the tick function you are only updating the circle but not the text, you should be updating both:
//update circle
d3.selectAll("circle").each(collide(.2))
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; });
//update tick
d3.selectAll("text").each(collide(.2))
.attr("x", function (d) { return d.x -20; })
.attr("y", function (d) { return d.y; });
working code here
Post a Comment for "Adding Text To D3 Circle"