In this part, we will talk about visualizing our network.
In Part 1 of this tutorial, we talked of a graph having 5 nodes (a,b,c,d,e) and the edges [(a,b), (b,c), (c,d)]. Let’s add one more edge (b,d)
Matplotlib is a set of plotting tools for python. You can download and install it from a package manager of your choice, or install it from source. This can take care of advanced 2D plotting for python. We will use this to plot our network.
#!/usr/bin/python import networkx as nx import matplotlib.pyplot as plt graph=nx.Graph() edgeList=[('a','b'), ('b','c'),('c','d'), ('b','d')] graph.add_edges_from(edgeList) pos=nx.spring_layout(graph) #specify the layout nx.draw(graph,pos,node_color='#A0CBE2', edge_color='#B0C23E',width=2, edge_cmap=plt.cm.Blues,with_labels=True) plt.show() #display the graph plt.savefig("idiot_network:P.png") #save it on the disk
All the parameters in nx.draw() are self explanatory.
NetworkX has the following layouts:
- Graphviz and pydot layout
- circular layout (places nodes in a circle)
- random layout (positions nodes based on an uniform distribution in a unit square.
- shell layout (places nodes in concentric circles)
- spring layout (places nodes using Fruchterman-Reingold force-directed algorithm )
- spectral layout (positions nodes using eigen vectors of the graph laplacian)
You can tinker with different layouts and select the one that best suits your needs.
To show you the types of visualizations rendered, I am posting some renders below :
In the next parts, we will work on some real network, like twitter followers network or IMDB co-star network or DBLP co-authorship network and check models for link prediction, homophily, information cascades and epidemics, community detection etc. Thanks for following this tut.