gpt4 book ai didi

javascript - 如何找到所有选定节点的相邻节点和边缘? D3

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:24:31 25 4
gpt4 key购买 nike

我有一个力导向图,可以双击一个节点,只显示该节点及其邻居,其余的给定一个隐藏类 -> 可见性:隐藏

但这只适用于一个节点。我可以选择多个节点并为它们提供一个 selectedNode 类。

现在我希望发生的是在具有 selectedNode 类的所有节点上使用此相邻算法。这样所有选定的节点和连接它们的边仍会显示,而未选定的节点和边将被隐藏。

这是我显示/隐藏边缘的方式。同样,这仅适用于一个节点 d3.select(this).node().__data__;。我试过 d = d3.selectAll("selectedNode").data(); 但运气不好 :(

var linkedByIndex = {};//Create an array logging what is connected to what

for (i = 0; i < graph.data.nodes.length; i++) //-populate the array
{
linkedByIndex[i + "," + i] = 1;
};


graph.data.edges.forEach(function (d) //-checks what nodes are related in array
{
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});


//-------------------------check if nodes are linked
function neighboring(a, b) //This function looks up whether a pair are neighbours
{
return linkedByIndex[a.index + "," + b.index];
}

d = d3.select(this).node().__data__;


links.classed("hidden", function (o) {
return d.index==o.source.index | d.index==o.target.index ? false : true;
});

添加代码

var links = inner.selectAll(".link").append("g")
.data(force.links())
.enter().append("line")
.attr("id", "links")
.attr("class", "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; })
.style("marker-end", "url(#arrow)") //adds arrows, main code on SVG append towards bottom
.style("stroke-width", lineWidth)
;

最佳答案

我认为这里有两个问题,由于您缺乏细节,我将做出假设。

1) 你有一个方法来检查两个节点是否是邻居。这是一个好的开始,但这还不够,您还需要一种方法来告诉您任何给定节点是选定节点还是它的邻居之一。假设您在 selected 数组中维护选定节点的列表,下面是这样一个函数在简单实现中的样子:

function shouldBeVisible(nodeIndex){
// visible if either selected itself or neighbour of a selected node
return selected.some(function(d){
// assuming you don't care about the direction of your edges
return linkedByIndex[nodeIndex+','+d]+linkedByIndex[d+','+nodeIndex];
});
}

您甚至可以重载此方法以使其“边缘友好”:

function shouldBeVisible(sourceIndex, targetIndex){
if (targetIndex !== undefined)
return shouldBeVisible(sourceIndex)
&& shouldBeVisible(targetIndex);
else return selected.some(function(d){
return linkedByIndex[sourceIndex+','+d]
+ linkedByIndex[d+','+sourceIndex];
});
}

请注意,如果您不在数据结构中维护选定的节点,您应该能够使用 d3.selectAll('.selectedNode') 轻松检索它们。您可能想为边缘实现类似的方法。

2) 你只是根据 first node in the selection 检查邻居而不是 all nodes in the selection .无论哪种方式,假设 links 准确描述了它所指的内容,您都不必费心这样做。

尝试这样的事情:

links.classed("hidden", function(d) {
return !shouldBeVisible(d.source.index, d.target.index);
});

关于javascript - 如何找到所有选定节点的相邻节点和边缘? D3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27546809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com