Networkx中特定节点标签设置

23 投票
1 回答
31695 浏览
提问于 2025-04-17 14:33

我想画一个网络图,除了某些特定的节点外,其他节点都不想标记。

我现在的代码大概是这样的:

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

目前这段代码可以改变节点的大小和颜色,列表中的节点我想给它们加上标签。

我试着添加标签的参数,并把它的值设置为中心节点的名字,但没有成功。

谢谢!

1 个回答

50

根据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')

我得到了我想要的效果,结果如下所示:

enter image description here

希望这能帮助像我一样的Python和networkx新手 :)

再次感谢Bula!

撰写回答