How to draw subgraph using networkx

前端 未结 1 1044
梦如初夏
梦如初夏 2021-01-03 05:16

I try to draw subgraph from karate_club_graph in networkx based on a list of nodes\'name but failed. How could draw subgraph as I want to show?

import networ         


        
相关标签:
1条回答
  • 2021-01-03 05:30

    The problem you're having is that your subgraph command is telling it to make a subgraph with a nodelist where each element is not just the node name, but also the data about that node name. The command G.subgraph needs just the list of node names.

    The easiest way to fix this is just

    k = G.subgraph(res)
    

    which will work even if some of the nodes in res aren't in G.

    I'll do this change and also show how to draw several times with consistent positions by adding an additional subgraph to plot. It will plot your k and then the subgraph made up of all nodes not in k. Note that no edges will exist between the two because of how subgraph works.

    import networkx as nx
    from matplotlib import pylab as pl
    
    G = nx.karate_club_graph()
    res = [0,1,2,3,4,5, 'parrot'] #I've added 'parrot', a node that's not in G
                                  #just to demonstrate that G.subgraph is okay
                                  #with nodes not in G.    
    pos = nx.spring_layout(G)  #setting the positions with respect to G, not k.
    k = G.subgraph(res)  
    
    pl.figure()
    nx.draw_networkx(k, pos=pos)
    
    othersubgraph = G.subgraph(range(6,G.order()))
    nx.draw_networkx(othersubgraph, pos=pos, node_color = 'b')
    pl.show()
    

    enter image description here

    The effect of having data=True in the G.nodes() call is as follows:

    print G.nodes()
    > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
    print G.nodes(data=True)
    > [(0, {'club': 'Mr. Hi'}), (1, {'club': 'Mr. Hi'}), (2, {'club': 'Mr. Hi'}), (3, {'club': 'Mr. Hi'}), (4, {'club': 'Mr. Hi'}), (5, {'club': 'Mr. Hi'}), (6, {'club': 'Mr. Hi'}), (7, {'club': 'Mr. Hi'}) ...  *I've snipped stuff out*
    

    So G.nodes() just gives the node names. G.nodes(data=True) gives a list of tuples, which have node name as the first entry and a dict showing any data about those nodes in the second entry.

    0 讨论(0)
提交回复
热议问题