简体   繁体   中英

How to filter nodes with specifc attribute and preserve the path using networkx graph

These days I am working on networkx graph. Let us say I have this graph. Priority 1 with the blue nodes, priority 2 with the yellow nodes, priority 3 with purple nodes, and priority 4 with green nodes.

在此处输入图像描述

I would like to filter by priority level. For example the first priority 1, it should filter nodes with blule color. I would like to keep nodes with blue color (priority 1) and ignore the rest, And it should look like this.

在此处输入图像描述

And for priority 2, including nodes for priority, it should show nodes with the yellow color. Keeping priority 1 (with blue color) and priority 2 (yellow color). Here I should keep the path from 10 to 190 since there is a path from the ignored nodes. And it should look like this.

在此处输入图像描述

And the same for priority 3 and 4. For example for priority 3, I would like to keep priority 1, 2, and 3 together as I showed at priority level 2.

This how I started.

collector = nx.DiGraph()
for n1, atrr1 in g1.nodes(data ='True'):
    for n2, atrr2 in g1.nodes(data ='True'):
        if ((g1.node[n1]['priority'] ==1) & (g1.node[n2]['priority'] ==2)):

            if (has_path(g1,n1, n2)):
                collector.add_edge(n1,n2)

        if ((g1.node[n2]['priority'] ==2) & (g1.node[n1]['priority'] ==2)):

            if (has_path(g1,n1, n2)):
                collector.add_edge(n1,n2) 


nx.draw(collector, with_labels = True, pos = nx.spring_layout(collector))
plt.rcParams["figure.figsize"] = [6,6]
plt.axis('off')
plt.show()

Can anyone help me to do this in python?

One way to do it would be to compute the graph reachability matrix (square matrix that has a 1 in row a , column b if node b is reachable from node a via the graphs edges). You can find how to implement this here . Then, all you have to do is filter out the nodes you want and re-draw the edges just for the filtered nodes using the computed matrix (by going over only the rows and columns corresponding to nodes that appear in the new graph and drawing an edge where there is a 1 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM