在d3力图中查找相邻节点

时间:2014-07-11 17:37:54

标签: javascript d3.js force-layout

我知道这个问题已被多次询问,但似乎我的数据设置方式使得这个问题变得更加困难。我试图选择与鼠标悬停的节点相邻的节点,这样我就可以降低非相邻节点的不透明度。我设法对链接做了这个没有任何问题。

我已经多次尝试重写Mike Bostock的解决方案here,但没有任何效果。最多,当我将鼠标悬停在上面时,我可以让每个节点淡出,这没有用。 Google小组中的This comment让我觉得我需要在节点数据中有一个节,告诉节点连接的其他节点。我的JSON目前看起来像这样:

节点:

[
  {
    "id":0,
    "name":"Test Writer 1"
  },
  {
    "id":1,
    "name":"Test Writer 2"
  }
]

链接:

[
  {
    "relationship":"Teacher/student",
    "source":73, //These numbers align to the ids and index of the nodes
    "target":74
  },
  {
    "relationship":"Teacher/student",
    "source":73,
    "target":75
  }
]

我认为最简单的解决方案是将链接数据添加到节点JSON,就像Google小组评论建议的那样。但是,我不认为我可以通过我绘制的数据库的方式来设置(虽然我对SQL非常不好,所以我并不乐观。真正。)。我也没有权限编辑数据库;我只能选择。

这是相邻节点代码的当前状态,它根本不做任何事情:

        var hash_lookup = [];
        nodesData.forEach(function(d, i) {
          hash_lookup[d.id] = d;
        });
        linksData.forEach(function(d, i) {
          d.source = hash_lookup[d.source];
          d.target = hash_lookup[d.target];
        });


        function neighboring(a, b) {
          return hash_lookup[a.index + "," + b.index];
        }

这里是fiddle.

我是编码的新手,所以我不确定我是否在某个地方犯了一个愚蠢的错误。我已经在一周的大部分时间里一直在努力,但我自己并没有取得任何进展。任何帮助表示赞赏。

修改

这是代码的另一个版本,改编自Mike Bostock的解决方案:

var linkedByIndex = {};
linksData.forEach(function(d) {
  linkedByIndex[d.source.index + "," + d.target.index] = 1;
});

function neighboring(a, b) {
  return linkedByIndex[a.index + "," + b.index];
}

node.on("mouseover.four", function () {
    node.style("opacity", function(d,o) {
  return neighboring(d, o) ? 1 : 0.3;
});
});

编辑2:

这是解决方案。您必须在调用强制函数后放置代码,否则它将无法工作:

force
            .nodes(nodesData)
            .links(linksData)
            .on("tick", tick)
            .start();

node.on("mouseover", fade(.1))
    .on("mouseout", fade(1));

var linkedByIndex = {};

linksData.forEach(function(d) {
  linkedByIndex[d.source.index + "," + d.target.index] = 1;
});

function isConnected(a, b) {
    return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index] || a.index == b.index;
}

function tick() {
//code code code//
}

    function fade(opacity) {
        return function(d) {
            node.style("stroke-opacity", function(o) {
                thisOpacity = isConnected(d, o) ? 1 : opacity;
                this.setAttribute('fill-opacity', thisOpacity);
                return thisOpacity;
            });

            link.style("stroke-opacity", opacity).style("stroke-opacity", function(o) {
                return o.source === d || o.target === d ? 1 : opacity;
            });
        };
    };

0 个答案:

没有答案
相关问题