Networkx Tutorial
Networkx Tutorial
Release 1.7
Contents
1 2 3 4 5 6 Creating a graph Nodes Edges What to use as nodes and edges Accessing edges Adding attributes to graphs, nodes, and edges 6.1 Graph attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Node attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3 Edge Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Directed graphs Multigraphs Graph generators and graph operations i ii ii iii iv iv iv v v v vi vi vii vii
7 8 9
1 Creating a graph
Create an empty graph with no nodes and no edges.
>>> import networkx as nx >>> G=nx.Graph()
By denition, a Graph is a collection of nodes (vertices) along with identied pairs of nodes (called edges, links, etc). 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. (Note: Pythons None object should not be used as a node as it determines whether optional function arguments have been assigned in many functions.)
2 Nodes
The graph G can be grown in several ways. NetworkX includes many graph generator functions and facilities to read and write graphs in many formats. To get started though well look at simple manipulations. You can add one node at a time,
>>> G.add_node(1)
or add any nbunch of nodes. An nbunch is any iterable container of nodes that is not itself a node in the graph. (e.g. a list, set, graph, le, etc..)
>>> H=nx.path_graph(10) >>> G.add_nodes_from(H)
Note that G now contains the nodes of H as nodes of G. In contrast, you could use the graph H as a node in G.
>>> G.add_node(H)
The graph G now contains H as a node. This exibility is very powerful as it allows graphs of graphs, graphs of les, graphs of functions and much more. It is worth thinking about how to structure your application so that the nodes are useful entities. Of course you can always use a unique identier in G and have a separate dictionary keyed by identier to the node information if you prefer. (Note: You should not change the node object if the hash depends on its contents.)
3 Edges
G can also be grown by adding one edge at a time,
>>> G.add_edge(1,2) >>> e=(2,3) >>> G.add_edge(*e) # unpack edge tuple*
or by adding any ebunch of edges. An ebunch is any iterable container of edge-tuples. An edge-tuple can be a 2tuple of nodes or a 3-tuple with 2 nodes followed by an edge attribute dictionary, e.g. (2,3,{weight:3.1415}). Edge attributes are discussed further below
>>> G.add_edges_from(H.edges())
One can demolish the graph in a similar fashion; Graph.remove_nodes_from(), Graph.remove_edge() and e.g.
>>> G.remove_node(H)
There are no complaints when adding existing nodes or edges. For example, after removing all nodes and edges,
>>> G.clear()
we add new nodes/edges and NetworkX quietly ignores any that are already present.
>>> >>> >>> >>> >>> G.add_edges_from([(1,2),(1,3)]) G.add_node(1) G.add_edge(1,2) G.add_node("spam") # adds node "spam" G.add_nodes_from("spam") # adds 4 nodes: s, p, a, m
At this stage the graph G consists of 8 nodes and 2 edges, as can be seen by:
>>> G.number_of_nodes() 8 >>> G.number_of_edges() 2
When creating a graph structure (by instantiating one of the graph classes you can specify data in several formats.
>>> H=nx.DiGraph(G) # create a DiGraph using the connections from G >>> H.edges() [(1, 2), (2, 1)] >>> edgelist=[(0,1),(1,2),(2,3)] >>> H=nx.Graph(edgelist)
5 Accessing edges
In addition to the methods Graph.nodes(), Graph.edges(), and Graph.neighbors(), iterator versions (e.g. Graph.edges_iter()) can save you from creating large lists when you are just going to iterate through them anyway. Fast direct access to the graph data structure is also possible using subscript notation. Warning: Do not change the returned dictit is part of the graph data structure and direct manipulation may leave the graph in an inconsistent state.
>>> G[1] # Warning: do not change the resulting dict {2: {}} >>> G[1][2] {}
You can safely set the attributes of an edge using subscript notation if the edge already exists.
>>> G.add_edge(1,3) >>> G[1][3][color]=blue
Fast examination of all edges is achieved using adjacency iterators. Note that for undirected graphs this actually looks at each edge twice.
>>> >>> >>> ... ... ... (1, (2, (3, (4, FG=nx.Graph() FG.add_weighted_edges_from([(1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)]) for n,nbrs in FG.adjacency_iter(): for nbr,eattr in nbrs.items(): data=eattr[weight] if data<0.5: print((%d, %d, %.3f) % (n,nbr,data)) 2, 0.125) 1, 0.125) 4, 0.375) 3, 0.375)
Note that adding a node to G.node does not add it to the graph, use G.add_node() to add new nodes.
The special attribute weight should be numeric and holds values used by algorithms requiring weighted edges.
7 Directed graphs
The DiGraph class provides additional methods specic to directed edges, e.g. DiGraph.out_edges(), DiGraph.in_degree(), DiGraph.predecessors(), DiGraph.successors() etc. To allow algorithms to work with both classes easily, the directed versions of neighbors() and degree() are equivalent to successors() and the sum of in_degree() and out_degree() respectively even though that may feel inconsistent at times.
>>> DG=nx.DiGraph() >>> DG.add_weighted_edges_from([(1,2,0.5), (3,1,0.75)]) >>> DG.out_degree(1,weight=weight) 0.5 >>> DG.degree(1,weight=weight) 1.25 >>> DG.successors(1) [2] >>> DG.neighbors(1) [2]
Some algorithms work only for directed graphs and others are not well dened for directed graphs. Indeed the tendency to lump directed and undirected graphs together is dangerous. If you want to treat a directed graph as undirected for some measurement you should probably convert it using Graph.to_undirected() or with
>>> H= nx.Graph(G) # convert H to undirected graph
8 Multigraphs
NetworkX provides classes for graphs which allow multiple edges between any pair of nodes. The MultiGraph and MultiDiGraph classes allow you to add the same edge twice, possibly with different edge data. This can be powerful for some applications, but many algorithms are not well dened on such graphs. Shortest path is one example. Where results are well dened, e.g. MultiGraph.degree() we provide the function. Otherwise you should convert to a standard graph in a way that makes the measurement well dened.
>>> >>> >>> {1: >>> >>> ... ... ... ... >>> [1, MG=nx.MultiGraph() MG.add_weighted_edges_from([(1,2,.5), (1,2,.75), (2,3,.5)]) MG.degree(weight=weight) 1.25, 2: 1.75, 3: 0.5} GG=nx.Graph() for n,nbrs in MG.adjacency_iter(): for nbr,edict in nbrs.items(): minvalue=min([d[weight] for d in edict.values()]) GG.add_edge(n,nbr, weight = minvalue) nx.shortest_path(GG,1,3) 2, 3]
5. Reading a graph stored in a le using common graph formats, such as edge lists, adjacency lists, GML, GraphML, pickle, LEDA and others.
>>> nx.write_gml(red,"path.to.file") >>> mygraph=nx.read_gml("path.to.file")
10 Analyzing graphs
The structure of G can be analyzed using various graph-theoretic functions such as:
>>> G=nx.Graph() >>> G.add_edges_from([(1,2),(1,3)]) >>> G.add_node("spam") # adds node "spam" >>> nx.connected_components(G) [[1, 2, 3], [spam]] >>> sorted(nx.degree(G).values()) [0, 1, 1, 2] >>> nx.clustering(G) {1: 0.0, 2: 0.0, 3: 0.0, spam: 0.0}
Functions that return node properties return dictionaries keyed by node label.
>>> nx.degree(G) {1: 2, 2: 1, 3: 1, spam: 0}
For values of specic nodes, you can provide a single node or an nbunch of nodes as argument. If a single node is specied, then a single value is returned. If an nbunch is specied, then the function will return a dictionary.
>>> 2 >>> 2 >>> {1: >>> [1, >>> [0, nx.degree(G,1) G.degree(1) G.degree([1,2]) 2, 2: 1} sorted(G.degree([1,2]).values()) 2] sorted(G.degree().values()) 1, 1, 2]
11 Drawing graphs
NetworkX is not primarily a graph drawing package but basic drawing with Matplotlib as well as an interface to use the open source Graphviz software package are included. These are part of the networkx.drawing package and will be imported if possible. See /reference/drawing for details. Note that the drawing package in NetworkX is not yet compatible with Python versions 3.0 and above.
You may nd it useful to interactively test code using ipython -pylab, which combines the power of ipython and matplotlib and provides a convenient interactive mode. To test if the import of networkx.drawing was successful draw G using one of
>>> >>> >>> >>> nx.draw(G) nx.draw_random(G) nx.draw_circular(G) nx.draw_spectral(G)
when drawing to an interactive display. Note that you may need to issue a Matplotlib
>>> plt.show()
command if you are not using matplotlib in interactive mode: (See Matplotlib FAQ ) To save drawings to a le, use, for example
>>> nx.draw(G) >>> plt.savefig("path.png")
writes to the le path.png in the local directory. If Graphviz and PyGraphviz, or pydot, are available on your system, you can also use
>>> nx.draw_graphviz(G) >>> nx.write_dot(G,file.dot)