在d3.js中向节点添加标签

时间:2013-02-26 06:24:01

标签: javascript d3.js label force-layout

我是d3.js的新手

我正在尝试为节点添加标签。 但无论我尝试什么都不行.. 我的代码在这里:

http://jsfiddle.net/Ymtg5/1/

它是http://bl.ocks.org/christophermanning/4208494之间的混搭 并强制有向图。 基本上我正在读一个json文件并创建所述图形。 现在我想向节点添加标签,就像http://bl.ocks.org/mbostock/950642一样 我尝试添加这些行

node.append("text")
      .attr("dx", 12)
      .attr("dy", ".35em")
      .text(function(d) { return d.name });

但它不起作用。 任何帮助。建议.. 感谢

1 个答案:

答案 0 :(得分:0)

最有可能的问题是您的JSON类没有“名称”。

是的,这不是问题

您的代码的相关部分如下:

var node = svg.selectAll("path.node")
    .data(nodes)
    .enter().append("path").attr("class", "node")
    .style("fill", function(d) { return fill(d.value); })
    .style("stroke", function(d) { return d3.rgb(fill(d.value)).darker(); })
    .call(force.drag);

 // HERE should go node manipulation to add the text

force
    .nodes(nodes)
    .links(links)
    .on("tick", tick)
    .start();

function tick() {

  //node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; );
  node.attr("d", function(d) { return clip({"type":"F {"type":"Point","coordin...         
  link.attr("d", function(d) { return clip({"type":"Feature","geometry":{ ...

如果要向节点添加标签,我已插入了应该进行节点操作的注释行。你是在tick函数内部做的(好吧,我认为你试图在那里做,代码不在小提琴中),并且该函数应该仅用于操纵节点的attr。创建文本并将其附加到节点的位置在函数之外。

相关问题