TL/DR:这样做:
pos = nx.spring_layout(g)
h = g.subgraph(A)
nx.draw_networkx_nodes(h,pos=pos, node_color='b') #or even nx.draw(h,pos=pos,node_color='b') to get nodes and edges in one command
nx.draw_networkx_edges(h,pos=pos)
完整答案:
您只想绘制A 中的节点和路径中的边。实际上,您可以完全避免使用noCor,使用指定要绘制哪些节点的nodelist 争论。
nx.draw_networkx_nodes(g,pos=pos, nodelist = A, node_color = 'b')
要仅绘制与A 对应的边,您需要弄清楚它们是什么。我知道的最简单的方法是
h = g.subgraph(A)
那么h是在节点A上诱导的子图。它在A 中具有所有优势。我有 99.9% 的把握(但尚未通过正式证明检查)如果 A 是两个节点之间的最短路径(由 Dijkstra 返回),那么在 A 中的节点之间没有任何其他边除了路径中的那些。所以h.edges() 将为A 提供优势。
nx.draw_networkx_edges(g,pos=pos, edgelist = h.edges())
更紧凑的形式会这样做:
pos = nx.spring_layout(g)
h = g.subgraph(A)
nx.draw_networkx_nodes(h,pos=pos, node_color='b') #or even nx.draw(h,pos=pos,node_color='b') to get nodes and edges in one command
nx.draw_networkx_edges(h,pos=pos)
您可能会问,为什么我将 pos 定义为 g 而不是 h。这是因为您可能想稍后将g 中的一些其他节点绘制到您的图形或其他图形中,然后保持一致的位置很有用。如果您只是针对h 进行操作,它基本上会想要创建一条直线。
您的命令 nx.draw_networkx_nodes(g, pos=pos, node_color=noCor) 上的一些 cmets。这告诉它使用来自noCor 的颜色绘制g 中的所有节点[并且它将根据颜色出现在noCor 中的顺序和节点出现在g.nodes() 中的顺序为节点着色]。最后,请注意您需要使用 matplotlib 可以识别的颜色(请参阅http://matplotlib.org/api/colors_api.html)。在这种情况下:
noCor = ["b" if n in A else "r" for n in g.nodes()]