Search code examples
pythonnetworkx

Networkx in Python - draw node attributes as labels outside the node


I have a graph of nodes with specific attributes and I want to draw the graph by networkx in Python with several attributes as labels of nodes outside the node.

Can someone help me how can I write my code to achieve this aim?

There is a loop in my code which generate "interface_?" attribute for each input from firewall list (fwList)

for y in fwList:
    g.add_node(n, type='Firewall')
    print 'Firewall ' + str(n) + ' :' 
    for x in fwList[n]:
        g.node[n]['interface_'+str(i)] = x
        print 'Interface '+str(i)+' = '+g.node[n]['interface_'+str(i)]
        i+=1
    i=1
    n+=1

Then, later on I draw nodes and edges like:

pos=nx.spring_layout(g)
nx.draw_networkx_edges(g, pos)
nx.draw_networkx_nodes(g,pos,nodelist=[1,2,3],node_shape='d',node_color='red')

and will extended it to some new nodes with other shape and color later.

For labeling a single attribute I tried below code, but it didn't work

labels=dict((n,d['interface_1']) for n,d in g.nodes(data=True))

And for putting the text out of the node I have no idea...


Solution

  • You have access to the node positions in the 'pos' dictionary. So you can use matplotlib to put text wherever you like. e.g.

    In [1]: import networkx as nx
    
    In [2]: G=nx.path_graph(3)
    
    In [3]: pos=nx.spring_layout(G)
    
    In [4]: nx.draw(G,pos)
    
    In [5]: x,y=pos[1]
    
    In [6]: import matplotlib.pyplot as plt
    
    In [7]: plt.text(x,y+0.1,s='some text', bbox=dict(facecolor='red', alpha=0.5),horizontalalignment='center')
    Out[7]: <matplotlib.text.Text at 0x4f1e490>
    

    enter image description here