Basic networkx


In [1]:
import networkx as nx

In [2]:
G = nx.DiGraph() # directed Graph

In [3]:
G.add_edge( 1,2 )  # nodes will be automatically created from edges
G.nodes()


Out[3]:
[1, 2]

In [4]:
myedges = [ (2,1), (3,1), (1,3) ] # a list of tuples
G.add_edges_from( myedges ) # ading edges from a list of tuples
G.nodes()


Out[4]:
[1, 2, 3]

Plotting the Graph


In [13]:
pos = nx.spring_layout(G) # positions for all node
nx.draw(G, pos, node_color = '#A0CBE2', width=1, with_labels=1)


Edges Properties

When calling nodes, we obtain the edges and its properties


In [5]:
G[1] # node 1 is connected to 2 and 3


Out[5]:
{2: {}, 3: {}}

In [14]:
G.neighbors(1) # to check only connected nodes


Out[14]:
[2, 3]

In [6]:
G[1][3]['prob'] = 0.25 # setting a 'probability' item to edge 1-3
G[1]


Out[6]:
{2: {}, 3: {'prob': 0.25}}

In [7]:
G[1][3].items() # see their edges properties as a list of tuples


Out[7]:
[('prob', 0.25)]

In [15]:
G.add_weighted_edges_from([ (3, 4, 0.5) ]) # setting weight and creating a new node (4)
G[3]


Out[15]:
{1: {}, 4: {'weight': 0.5}}

Iterations


In [17]:
H = nx.DiGraph() # create a new graph
H.add_edges_from(G.edges(), weigth=0.5) # use edges of G to create H with weigth 0.5

In [18]:
H.edges()


Out[18]:
[(1, 2), (1, 3), (2, 1), (3, 1), (3, 4)]

Fast iteration of edges with adjacent interators with .adjacent_iter()


In [21]:
for node, neighbor in H.adjacency_iter(): # adjacentcy_iter return a dictionary with the  edges
    print(node, neighbor) # dictionary of dictionaries, get


(1, {2: {'weigth': 0.5}, 3: {'weigth': 0.5}})
(2, {1: {'weigth': 0.5}})
(3, {1: {'weigth': 0.5}, 4: {'weigth': 0.5}})
(4, {})

List of attributes of the Graph


In [22]:
for node, neighbor in H.adjacency_iter():
    for n, myattdict in neighbor.items():
        print( myattdict['weigth'] )


0.5
0.5
0.5
0.5
0.5

List all edeges and its attributes


In [23]:
for node, neighbor in H.adjacency_iter():
    for n, myattdict in neighbor.items():
        if myattdict['weigth'] < 0.6: 
            print(node, n, myattdict['weigth'])


(1, 2, 0.5)
(1, 3, 0.5)
(2, 1, 0.5)
(3, 1, 0.5)
(3, 4, 0.5)

In [ ]: