Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Networkx specific nodes labeling

I want to draw a network and I want it to be unlabeled with the exception for cretin nodes.

What I have at the moment is something like this:

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

The code at the moment changes the size and color of the nodes in the hubs list. I'd like to label them as well.

I tried to add the label argument and set its value to the hub name. but it did't work.

Thanks

like image 805
amaatouq Avatar asked Feb 02 '13 19:02

amaatouq


Video Answer


1 Answers

From Bula's comment the solution is quite easy

The trick is to set the labels in a dictionary where the key is the node name and the value is the label you require. Therefore to label only the hubs, the code will be something similar to this:

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

I got what I wanted which is the following: enter image description here

I hope this would help other python/networkx newbies like myself :)

Again, Thanks Bula

like image 106
amaatouq Avatar answered Sep 29 '22 15:09

amaatouq