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)


Calling Nodes

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


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

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