将图节点的相对位置投影到绝对坐标

时间:2015-12-13 02:24:49

标签: javascript algorithm d3.js graph graph-theory

我有这样的数据结构:

nodes = [
         {
          "id":0,
          "proximities":{
             "1": 12.34,
             "2": 56.78
           }, 
         {
          "id":1,
          "proximities":{
             "0": 12.34,
             "2": 90.12
           }, 
         {
          "id":2,
          "proximities":{
             "0": 56.78,
             "1": 90.12
           }, 
      ]

这是我想要放在屏幕上的节点数组。每个节点包含一组“邻近”,到其他节点的数字距离,我想使用这些距离来计算显示节点的绝对XY位置。 也就是说,我们希望在算法上计算一种布局,其中每对节点之间的距离尽可能接近数据中给出的距离。

我已经将这个问题标记为d3,因为我将使用d3绘制图形,并且对它所具有的任何内置功能感到好奇,这可能使我更容易。

那就是说,我的问题的根源更广泛:我在这里尝试做的是否有名称?我确信有解决这个问题的图论方法,但我找不到它们是因为我不确定这个问题是什么。我该怎么用Google?

1 个答案:

答案 0 :(得分:1)

以下是我处理问题集的方法。

我的节点及其相似之处如下:

nodes = [{
  "id": 0,
  name: "cyril",
  "proximities": {
    "1": 12.34,
    "2": 56.78,
    "3": 40
  }
}, {
  "id": 1,
  name: "tia",
  "proximities": {
    "0": 12.34,
    "2": 90.12
  }
}, {
  "id": 2,
  name: "josh",
  "proximities": {
    "0": 56.78,
    "1": 90.12
  }
}, {
  "id": 3,
  name: "sim",
  "proximities": {
    "0": 40,
  }
}]

将数据集更改为Force Layout D3可接受的格式。

function makeNodesLinks(nodes) {

  var graph = {};
  graph.nodes = [];
  graph.links = [];
  var keys = [];

  nodes.forEach(function(d) {
    //add node
    graph.nodes.push({
      name: d.name,
      id: d.id
    });
    for (var key in d.proximities) {
      if (keys.indexOf(d.id + "-" + key)<0)//this means if link is present don't add
      {
        keys.push(d.id + "-" + key);//done to make links unique
        keys.push(key + "-" + d.id);
        //add link and value stores its approx distance.
        graph.links.push({
          source: d.id,
          target: parseInt(key),
          value: d.proximities[key]
        });
      }
    }
  });
  return graph;
}

最后在力布局中,链接之间的距离由值键决定。

  force
    .nodes(graph.nodes)
    .links(graph.links)
    .linkDistance(function(d) {
      return d.value*3;//approx distance between 2 nodes.
    })
    .start();

工作代码here

现在,如果您不想看到链接,请更改CSS中的样式:将不透明度设为0,使其不可见。

.link {
  stroke: #999;
  stroke-opacity: 0;
}
相关问题