Networkx特定节点标记

ama*_*ouq 13 python networkx

我想画一个网络,我希望它没有标记,但cretin节点除外.

我现在所拥有的是这样的:

nx.draw(G, pos=pos, node_color='b', node_size=8, with_labels=False)

for hub in hubs:
     nx.draw_networkx_nodes(G, pos, nodelist=[hub[0]], node_color='r')
Run Code Online (Sandbox Code Playgroud)

此时代码会更改集线器列表中节点的大小和颜色.我也想给他们贴上标签.

我尝试添加label参数并将其值设置为集线器名称.但它没有用.

谢谢

ama*_*ouq 22

从Bula的评论来看,解决方案非常简单

诀窍是在字典中设置标签,其中键是节点名称,值是您需要的标签.因此,为了仅标记集线器,代码将类似于此:

labels = {}    
for node in G.nodes():
    if node in hubs:
        #set the node name as the key and the label as its value 
        labels[node] = node
#set the argument 'with labels' to False so you have unlabeled graph
nx.draw(G, with_labels=False)
#Now only add labels to the nodes you require (the hubs in my case)
nx.draw_networkx_labels(G,pos,labels,font_size=16,font_color='r')
Run Code Online (Sandbox Code Playgroud)

我得到了我想要的以下内容: 在此输入图像描述

我希望这会有助于像我这样的其他python/networkx新手:)

再次,谢谢布拉

  • 很高兴它有帮助,这些信息位于[文档](http://networkx.github.com/documentation/latest/reference/ generated/networkx.drawing.nx_pylab.draw_networkx.html#networkx.drawing.nx_pylab.draw_networkx)但是表达式不清楚,因此为了安全起见,您可以尝试或查看 `draw_networkx` [源代码行](https://github.com/networkx/networkx/blob/master/networkx/drawing/nx_pylab.py #L262)它调用“draw_networkx_labels”并且[那里](https://github.com/networkx/networkx/blob/master/networkx/drawing/nx_pylab.py#L698)它迭代字典制作标签。 (2认同)