Examining graph elements
NetworkX provides four basic properties to facilitate examining graphs.
G.nodes - to view nodes
G.edges - to view edges
G.adj - to view neighbor nodes of each node
G.degree - to view degree of each node
These provide a continually updated read-only view into the graph structure and help us understand the underlying network and its properties.
Now, we will create a sample graph using the below code.
import networkx as nx
graph_edges = [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 4), (3, 4)]
G = nx.Graph()
G.add_edges_from(graph_edges)
The graph we just created looks like the one below.
Now we will apply the four properties we discuss earlier to the above graph.
import networkx as nx
graph_edges = [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 4), (3, 4)]
G = nx.Graph()
G.add_edges_from(graph_edges)
print('Nodes:', end=' ')
print(G.nodes)
print('Edges:', end=' ')
print(G.edges)
print('Neighbors of 0:', end=' ')
print(list(G.adj[0]))
print('Degrees of nodes:', end=' ')
print(G.degree)
The output is as below.
Nodes: [0, 2, 3, 4, 1]
Edges: [(0, 2), (0, 3), (0, 4), (2, 1), (2, 4), (3, 1), (3, 4), (4, 1)]
Neighbors of 0: [2, 3, 4]
Degrees of nodes: [(0, 3), (2, 3), (3, 3), (4, 4), (1, 3)]
Removing graph elements
Removing nodes and edges of a graph are done in the same way as adding.
We can use remove_node(), remove_nodes_from(), remove_edge() and remove_edges_from() methods to remove nodes and/or edges from a graph.
We can remove the edge (2,4) from the earlier graph using the below code.
import networkx as nx
graph_edges = [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 4), (3, 4)]
G = nx.Graph()
G.add_edges_from(graph_edges)
G.remove_edge(2, 4)
The graph looks like this
Similarly, we can remove the node 4 using the below code.
import networkx as nx
graph_edges = [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 4), (3, 4)]
G = nx.Graph()
G.add_edges_from(graph_edges)
G.remove_node(4)
The graph then looks like this
Comments