python - NetworkX DiGraph按节点创建子图(DiGraph)

标签 python networkx subgraph

我想按节点获取一个子图(红色区域):
子图由从输入节点可到达的所有节点组成。

like G.subgraph(3) returns a new DiGraph from the red area.



enter image description here

例如,我这样创建一个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如图所示。 enter image description here

关于python - NetworkX DiGraph按节点创建子图(DiGraph),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32935510/

相关文章:

python - 颜色设置不会应用于图形绘制

python - 如何使用networkx绘制子图

Neo4J 子图或多数据库

python - Select2,为Single Select Drop down设置默认值

python - 使用 basemap warpimage 保持透明度

python - 图像合成

c++ - boost 中的子图和图连通性

python - 删除 BeautifulSoup 分解后变空的行

python - Networkx 自定义不起作用

python - 如何使用 networkx 从给定图中提取所有可能的诱导子图