Networkx specific nodes labeling

amaatouq picture amaatouq · Feb 2, 2013 · Viewed 15.5k times · Source

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

Answer

amaatouq picture amaatouq · Feb 3, 2013

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