1

My previous question is this How to display images based on their distance to the center image?? and someone suggest me to use d3.js. So here's my code from the documentation. I want to know how can I change these nodes with different images and is that possible to make the links with different distances?

<!DOCTYPE html>
    <meta charset="utf-8">
    <style>

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

    .node {
     fill: #000;
     stroke: #fff;
     stroke-width: 1.5px;
    }

    .node.a { fill: #ff7f0e; }
    .node.b { fill: #2ca02c; }
    .node.c { fill: #2ca02c; }
    .node.d { fill: #2ca02c; }


    </style>
    <body>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script>

    var width = 960,
        height = 500;

    var color = d3.scale.category10();

    var nodes = [],
        links = [];

    var force = d3.layout.force()
    .nodes(nodes)
    .links(links)
    .charge(-400)
    .linkDistance(120)
    .size([width, height])
    .on("tick", tick);

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

    var node = svg.selectAll(".node"),
    link = svg.selectAll(".link");


    setTimeout(function() {
     var a = {id: "a"}, b = {id: "b"}, c = {id: "c"},d = {id: "d"};

    nodes.push(a, b, c, d);
    links.push({source: a, target: b}, {source: a, target: c},{source: a, target: d});
    start();
    }, 0);



    function start() {
     link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });
     link.enter().insert("line", ".node").attr("class", "link");
     link.exit().remove();

     node = node.data(force.nodes(), function(d) { return d.id;});
     node.enter().append("circle").attr("class", function(d) { return "node " + d.id; }).attr("r", 8);
     node.exit().remove();

     force.start();
    }

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

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

    </script>

My final expected output should looks something like this:enter image description here

Community
  • 1
  • 1
user2462090
  • 119
  • 1
  • 1
  • 12

1 Answers1

0

You can adjust the distance between nodes using the linkDistance() function. The code would look something like this.

force.linkDistance(function(d) {
  return d.distance; // each link data element has a member "distance"
});

Note that these are only weak geometric constraints. This means that if you specify a distance of 10 between two nodes, the distance in the end may not be 10, but 12. If you need specific distances, the force layout is the wrong thing to use.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204