Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text to d3 circle

I am using this example http://bl.ocks.org/danielatkin/57ea2f55b79ae686dfc7 and I am trying to add some text in the circle.

This is how the circles are created and placed

    var nodes = svg.selectAll("circle")
       .data(data);

    nodes.enter().append("circle")
      .attr("class", function (d, i) { return "circle_"+d.sentiment+" circle_"+i})
      .attr("cx", function (d) { return d.x; })
      .attr("cy", function (d) { return d.x; })
      .attr("r", function (d) { return d.radius; })
      .style("fill", function (d, i) { return colors['default']; })
      .on("mouseover", function (d) { showPopover.call(this, d); })
          .on("mouseout", function (d) { removePopovers(this, true); })
          .call(pulse, function(d){ return d.radius+4; }, function(d){return d.radius; });

But I am getting no clue on how to add text to these circles.

I have already reffered this and this answer but couldn't succeed. The issue is that after following the above answers my circles stuck in a diagonal line.

Can someone tell me how to do this?

like image 993
void Avatar asked Sep 06 '25 09:09

void


1 Answers

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 g
    return "translate(" + d.x + "," + d.y + ")";
  });

Updated block.

like image 121
Mark Avatar answered Sep 09 '25 04:09

Mark