【问题标题】:adding labels to node in d3.js在 d3.js 中向节点添加标签
【发布时间】:2013-02-26 06:24:00
【问题描述】:

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

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

【问题讨论】:

    标签: javascript d3.js label force-layout


    【解决方案1】:

    问题很可能是您的 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 。创建文本并将其附加到节点的位置在函数之外。

    【讨论】:

    • 我的 json 文件看起来像这样 { "nodes":[ {"name":"Myriel","group":1}, {"name":"Napoleon","group":1 },.....
    • 对不起,没有看到对悲惨者的引用 :-) 你的代码是否包含在小提琴中?我找不到它
    • @vals.. 嗨,你可以从这里得到 miserables.json bost.ocks.org/mike/miserables/miserables.json
    • 没有json数据,我想知道你的代码'node.append("text")'在哪里
    • 第 163 行 .. 但我认为问题出在第 160 行 .. 已被评论,但这就是我认为要让这件事正常工作所需要的 .. 谢谢
    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 2013-10-31
    • 2019-01-15
    • 2022-07-04
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多