我想按节点获取一个子图(红色区域):
子图由从输入节点可到达的所有节点组成。
like G.subgraph(3) returns a new DiGraph from the red area.
例如,我这样创建一个DiGraph:
import networkx as nx
G = nx.DiGraph()
G.add_path([1,2,3,4])
G.add_path([3,'a','b'])
A = nx.to_agraph(G)
A.layout()
A.draw('graph.png')
我研究了https://networkx.github.io/documentation/latest/reference/generated/networkx.Graph.subgraph.html并将其转换为单向。我测试了out_egdes,strong/weak_connected_component,但从未成功。
我也看了How to find subgraphs in a directed graph without converting to undirected graph?和Networkx: extract the connected component containing a given node (directed graph)。
我知道Subgraph在DiGraph中不起作用。
有人可以告诉我该怎么做吗?如果结果图也是DiGraph会很好
最佳答案
根据我的理解,创建子图的标准取决于可从输入节点到达的节点。然后,以下递归函数应该足以完成工作。
def create_subgraph(G,sub_G,start_node):
for n in G.successors_iter(start_node):
sub_G.add_path([start_node,n])
create_subgraph(G,sub_G,n)
我复制了代码以创建图,初始化了一个空的有向图,并按如下所示调用了该函数:
G = nx.DiGraph()
G.add_path([1,2,3,4])
G.add_path([3,'a','b'])
sub_G = nx.DiGraph()
create_subgraph(G, sub_G,3)
所得的Digraph如图所示。
关于python - NetworkX DiGraph按节点创建子图(DiGraph),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32935510/