Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 750
Masood Avatar asked Jan 27 '13 12:01

Masood


People also ask

How do I color a specific node in NetworkX?

Node Color by Node Type Basically, we create another DataFrame where we specify the node ID and node type and use the pd. Categorical() method to apply a colormap.

Which data type can be used as the content of a node in NetworkX?

In NetworkX, nodes can be any hashable object e.g., a text string, an image, an XML object, another Graph, a customized node object, etc. Python's None object is not allowed to be used as a node.


2 Answers

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

like image 84
Aric Avatar answered Sep 28 '22 08:09

Aric


In addition to Aric's answer, the pos dictionary contains x, y coordinates in the values. So you can manipulate it, an example might be:

pos_higher = {}
y_off = 1  # offset on the y axis

for k, v in pos.items():
    pos_higher[k] = (v[0], v[1]+y_off)

Then draw the labels with the new position:

nx.draw_networkx_labels(G, pos_higher, labels)

where G is your graph object and labels a list of strings.

like image 24
gozzilli Avatar answered Sep 28 '22 07:09

gozzilli