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

标签 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 绘制图形,并且对它具有的任何内置功能感到好奇,这些功能可能会让我更轻松地完成这项工作。

也就是说,我的问题的根源更广泛:我在这里尝试做的事情有名称吗?我确信有图论方法可以解决这个问题,但我找不到它们,因为我不确定这个问题叫什么。我应该谷歌什么?

最佳答案

以下是我如何处理您的问题集。

我的节点和它们的邻近度是这样的:

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

关于javascript - 将图节点的相对位置投影到绝对坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34247363/

相关文章:

javascript - D3 v4 更新嵌套数据,最好的方法

javascript - svg 圆圈没有很好地注册鼠标悬停

javascript - 缩放html页面的部分内容

javascript - Chart.js 折线图数据不显示

Python 3 递归链表节点插入

d3.js - 尝试从 d3.js SVG 图上的 x 坐标检索 x 值

javascript - three.js pov 相机环视错误

javascript - Javascript 如何处理导出的模块级变量?

algorithm - (N x M) 图表问题

php - 间隔如何在php中以不同方式使用