1. Subgraphs
Awesome job with the previous exercises! Earlier on, we had mentioned the idea of
2. Subgraphs
"subgraphs" in the context of cliques. In the coming exercises, you will gain more practice with this idea. When you have a large graph, and you want to visualize just a small portion of it, it can be helpful to extract those nodes and their associated edges as a separate graph object. For example, you might want to visualize a particular path through the network, or you might want to visualize a particular community or clique. Alternatively, you might just want to explore the structure of the graph around a node going out a number of degrees of separation. In all of these scenarios, it's useful to be able to "slice out" the nodes and edges of interest, and visualize them.
3. Subgraphs
Let's take a look at how we might be able to do this. Let's say I have a graph G, made by the Erdos-Renyi graph generator in NetworkX. I can construct it by using the nx-dot-erdos_renyi_graph function, passing in n equals 20 (for the number of nodes in the graph), and p equals 0-point-2 (for the probability that an edge exists between a given pair of nodes). The graph is generated probabilistically, and in this instance, has 20 nodes, connected by 37 edges. Let's say I'm interested in plotting node 8 and its neighbors. I can first initialize a list called nodes, comprised of the neighbors of node 8. I can then append the node 8 to the list. To get the subgraph, of the five nodes, I can use the
4. Subgraphs
G-dot-subgraph function, passing in the nodes list, and assign the result to a new graph called G_eight. G_eight will have the nodes 8 and its neighbors, and the four edges that connect node 8 to its neighbors. In addition, it will contain the edges that exist between node 8's neighbors, such as the edge between node 2 and 10. If we check the data type of both graphs, we'll notice that they will both have the same data type.
5. Subgraphs
We can draw the subgraph of those nodes by using a familiar function, nx-dot-draw. Note that apart from passing in the graph object G_eight, we can also tell the draw function to draw the graph with node labels as well, to help with visualization.
6. Let's practice!
In the exercises, you'll be practicing the use of G-dot-subgraphs with a pre-defined list of nodes, and with graph queries that you've tried out in the first chapter. Go forth and have fun!