【问题标题】:D3 Force Directed JSON Adjacency ListD3 强制定向 JSON 邻接列表
【发布时间】:2014-02-14 04:51:07
【问题描述】:

我有一个图邻接列表,如下所示:

{
  nodes: [
  {
    "id": 1,
    "label": "Mark
  },...],

  edges: [
  {
    "source": 1,
    "target": 2
  },....]
}

边使用节点的id!

我一直在使用 PHP 将此列表回显到客户端。

D3 无法从文件加载我的 JSON。 所以我尝试手动解析它:

var width = window.innerWidth,
      height = window.innerHeight;

  var color = d3.scale.category20();

  var force = d3.layout.force()
      .linkDistance(40)
      .linkStrength(2)
      .charge(-120)
      .size([width, height]);

  var svg = d3.select("body").append("svg")
      .attr("width", width)
      .attr("height", height);

  var nodes = [], links = [];

  d3.json( null, function( error )
  {
    JSONData.nodes.forEach( function(node)
    {
      nodes.push( node );
    });

    JSONData.edges.forEach( function(edge)
    {
      links.push({source: edge.source, target: edge.target});
    });

    force.nodes(nodes)
     .links(links)
     .start();

    var link = svg.selectAll(".link")
          .data(links)
          .enter().append("path")
          .attr("fill", "none")
          .attr("class", "link");

    var node = svg.selectAll(".node")
          .data(nodes)
          .enter().append("circle")
          .attr("class", "node")
          .attr("r", 5)
          .style("fill", "#4682B4" )
          .call(force.drag);

    node.append("title").text(function(d) { return d.label; });

    force.on("tick", function() 
    {
      link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
    });
  });

但是,我只能看到节点,而不是边缘。 我添加了一个 CSS 文件:

.node {
  stroke: #4682B4;
  stroke-width: 1.5px;
}

.link {
  stroke: #ddd;
  stroke-width: 1.5px;
}

但无济于事。 有没有办法解决这个问题?

【问题讨论】:

    标签: javascript php json d3.js force-layout


    【解决方案1】:

    你需要使用:

          .enter().append("line")
    

    而不是

          .enter().append("path")
    

    (也许您还需要更改一些其他属性,以便它们对应于 line,而不是 path)。

    或者,您可以绘制一些更复杂的路径而不是直线,但我认为在您的情况下这将是矫枉过正。

    编辑:

    我刚刚发现了两个相关且有趣的问题:

    enter link description here - 描述了在强制布局中显示链接时的另一种问题 - 确保您没有遇到类似的障碍

    enter link description here - 一个试图绘制曲线而不是线条的人,如果你决定做类似的事情

    但希望cmet中的这个答案和提示足以让你得到你想要的。

    【讨论】:

    • 恐怕它仍然没有产生任何线条。保存链接的数组,需要引用节点ID,还是节点数组中的节点Index?
    • 文档 (github.com/mbostock/d3/wiki/Force-Layout#wiki-links) 似乎说应该使用节点数组的 INDEX 来初始化链接,而不是 Id。希望你已经弄清楚了。您现在设法完全解决了您的问题吗?
    • 不,我已经放弃它并使用 Sigma.js 无论如何感谢您的帮助!
    猜你喜欢
    • 2016-11-10
    • 2015-03-02
    • 2017-09-16
    • 2015-12-25
    • 2014-07-09
    • 2012-09-17
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多