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]:
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]:
In [13]:
pos = nx.spring_layout(G) # positions for all node
nx.draw(G, pos, node_color = '#A0CBE2', width=1, with_labels=1)
When calling nodes, we obtain the edges and its properties
In [5]:
G[1] # node 1 is connected to 2 and 3
Out[5]:
In [14]:
G.neighbors(1) # to check only connected nodes
Out[14]:
In [6]:
G[1][3]['prob'] = 0.25 # setting a 'probability' item to edge 1-3
G[1]
Out[6]:
In [7]:
G[1][3].items() # see their edges properties as a list of tuples
Out[7]:
In [15]:
G.add_weighted_edges_from([ (3, 4, 0.5) ]) # setting weight and creating a new node (4)
G[3]
Out[15]:
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]:
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
List of attributes of the Graph
In [22]:
for node, neighbor in H.adjacency_iter():
for n, myattdict in neighbor.items():
print( myattdict['weigth'] )
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'])
In [ ]: