向d3圆添加文字 [英] Adding text to d3 circle

查看:669
本文介绍了向d3圆添加文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此示例 http://bl.ocks.org/danielatkin/57ea2f55b79ae686dfc7并且我正在尝试在圈子中添加一些文本.

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?

推荐答案

另一个接近@cyril的选项是使用g元素,并将圆圈和文本都放入其中.这样可以节省两次数据绑定和两次移动更新:

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;
    });

并将节点在tick函数中的位置更新为:

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 + ")";
  });


更新了阻止.

这篇关于向d3圆添加文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆