您遇到的问题是您的子图命令告诉它创建一个带有nodelist的子图,其中每个元素不仅仅是节点名,还有关于该节点名的数据.命令G.subgraph只需要节点名称列表.
解决这个问题的最简单方法就是
k = G.subgraph(res)
即使res中的某些节点不在G中,它也能工作.
我将做这个改变,并通过在绘图中添加一个额外的子图来展示如何使用一致的位置绘制几次.它将绘制您的k,然后绘制由不在k中的所有节点组成的子图.请注意,由于子图的工作方式,两者之间不存在任何边.
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()
在G.nodes()调用中具有data = True的效果如下:
print G.nodes()