[英]How do I find neighboring nodes & edges of all selected nodes ? D3
我有一個力導向圖,可以雙擊一個節點,並且只顯示該節點及其鄰居,其余的則給出一個隱藏的類-> visiblity:hidden
但這僅適用於一個節點。 我可以選擇多個節點並為它們提供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)您只檢查選擇中的第一個節點而不是選擇中的所有節點的鄰域。 無論哪種方式,只要links
准確地描述了它所指的內容,您都不必費心做這件事。
嘗試這樣的事情:
links.classed("hidden", function(d) {
return !shouldBeVisible(d.source.index, d.target.index);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.