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*
2
3
by adding a list of edges,
G.add_edges_from([(1, 2), (1, 3)])
or by adding any ebunch (opens new window) of edges. An ebunch is any iterable container of edge-tuples. An edge-tuple can be a 2-tuple 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)
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'
G.add_edge(3, 'm')
2
3
4
5
6
At this stage the graph G
consists of 8 nodes and 3 edges, as can be seen by:
G.number_of_nodes()
G.number_of_edges()
2
We can examine the nodes and edges. Four basic graph properties facilitate reporting: G.nodes
, G.edges
, G.adj
and G.degree
. These are set-like views of the nodes, edges, neighbors (adjacencies), and degrees of nodes in a graph. They offer a continually updated read-only view into the graph structure. They are also dict-like in that you can look up node and edge data attributes via the views and iterate with data attributes using methods .items()
, .data('span')
. If you want a specific container type instead of a view, you can specify one. Here we use lists, though sets, dicts, tuples and other containers may be better in other contexts.
list(G.nodes)
list(G.edges)
list(G.adj[1]) # or list(G.neighbors(1))
G.degree[1] # the number of edges incident to 1
2
3
4
5
6
7
One can specify to report the edges and degree from a subset of all nodes using an nbunch. An nbunch is any of: None (meaning all nodes), a node, or an iterable container of nodes that is not itself a node in the graph.
G.edges([2, 'm'])
G.degree([2, 3])
2
3
One can remove nodes and edges from the graph in a similar fashion to adding. Use methods Graph.remove_node()
(opens new window), Graph.remove_nodes_from()
(opens new window), Graph.remove_edge()
(opens new window) and Graph.remove_edges_from()
(opens new window), e.g.
G.remove_node(2)
G.remove_nodes_from("spam")
list(G.nodes)
G.remove_edge(1, 3)
2
3
4
5
When creating a graph structure by instantiating one of the graph classes you can specify data in several formats.
G.add_edge(1, 2)
H = nx.DiGraph(G) # create a DiGraph using the connections from G
list(H.edges())
edgelist = [(0, 1), (1, 2), (2, 3)]
H = nx.Graph(edgelist)
2
3
4
5
6