How to draw a subgraph using networkx

I am trying to draw a subgraph from karate_club_graph in networkx based on the node'name list, but failed. How to draw a subgraph as I want to show?

import networkx as nx
from matplotlib import pylab as pl

G = nx.karate_club_graph()
res = [0,1,2,3,4,5]
new_nodes = []
for n in G.nodes(data=True):
  if n[0] in res:
    new_nodes.append(n)

k = G.subgraph(new_nodes)
pos = nx.spring_layout(k)

pl.figure()
nx.draw(k, pos=pos)
pl.show()
+4
source share
1 answer

The problem that you are facing is that your subgraph command tells it to make a subgraph with a nodelist, where each element is not only the name of the node, but also data about that node name. The command G.subgraphneeds only a list of node names.

The easiest way to fix this is simply

k = G.subgraph(res)

which will work even if some of the nodes in are resnot in G.

, , , . k, , , k. , , subgraph.

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 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

data=True G.nodes() :

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*

G.nodes() node. G.nodes(data=True) , node , dict .

+8

Source: https://habr.com/ru/post/1584405/


All Articles