How to Visualize Social Network With Graph Theory | by Khuyen Tran | Towards Data Science

After reading the books in the series A Song of Ice and Fired by G. R. R. Martin, as a true fan of Game of Thrones, you might be curious about who is the most influential person in Westeros. Or you know that Eddard Stark and Randyll Tarly are connected but not quite sure how exactly they are connected. Are they connected by a third, or fourth person? Would it be great if you can visualize the network?
As data enthusiastic, you decide to do a search on relevant data to analyze. Luckily, you find the data of character interaction networks for George R. R. Martin’s “A Song of Ice and Fire”. How exciting it is! But the data contains a list of nodes and edges. What do they even mean and where should you start? Don’t worry. I get your back. Let’s understand what is a graph and how the graph helps us to understand social networks.
A graph is a structure that contains vertices (or nodes) and each of the related pairs of vertices is called an edge. The edges may be directed or undirected. Directed means one direction. Person A might like person B but person B may not like person A. Undirected means 2 directions. If person A shakes hands with person B, that also means the person B shakes hands with the person A
With the structure of the graph, it can be utilized to visualize social networks efficiently. Want to know the influencer of members in a team? We can immediately see that the person (node) with the most connections (edges) is the influencer.
Great! We know why the graph is useful in visualizing the network. Let’s find out how we can create the graph and use it to visualize the network of characters in Game of Thrones!
I merged multiples data from several books into 2 files: data of nodes ‘ASOIAF_nodes.csv’, and data of edges ‘ASOIAF_edges.csv’. You can find the data here
import pandas as pdnodes = pd.read_csv('ASOIAF_nodes.csv')nodes = nodes['Id']num_nodes = nodes.shape[0]nodes
Cool! So we have a list of characters in the variable node. There is a total of 276 nodes (characters). Now let’s explore edges. In the ‘ASOIAF_edges.csv’ file, there is also information about weight (number of interactions), and the kind of graph (undirected). But since we simply care about the connections, we use the first 2 columns
edges = pd.read_csv('ASOIAF_edges.csv',usecols=[0,1] )edges
There is a total of 683 connections! Wow. Many connections established throughout the series. But how do we make these data into a graph? We can regard:
Each character as a vertex
Two connected vertices as an edge
Now we are ready to visualize the network!
Graphviz is a Python interface for drawing graphs. To install it, run
$ pip install graphviz
Create a graph by instantiating a new Digraph object
from graphviz import Digraphdot = Digraph(comment='VIP graph')
Let’s visualize the first ten nodes
nodes_G = []for node in edges[:10]['Source']:    if node not in nodes_G:        nodes_G.append(node)for node in edges[:10]['Target']:    if node not in nodes_G:        nodes_G.append(node)
Add nodes and edges into the graph
dot = Digraph(comment='VIP graph')for i in range(len(nodes_G)):    dot.node(nodes_G[i])for i in range(len(edges[:10])):    edge = edges.iloc[i]    dot.edge(edge['Source'], edge['Target'])
Visualize:
dot.render('VIP-graph_10.gv', view=True)
Nice! We can see the interactions between characters clearly in the graph. But how about visualizing the entire network. Of course, we can do that. But we should anticipate that the network of characters in 5 chapters of this series would be huge
dot = Digraph(comment='VIP graph')for i in range(num_nodes):    dot.node(nodes[i])for i in range(len(edges)):    edge = edges.iloc[i]    dot.edge(edge['Source'], edge['Target'])dot.render('VIP-graph.gv', view=True)
It is time for the show!
Cool! With graph, we can visualize the network efficiently. But can we create our own graph class?
Start with creating the vertex (node) class. What attributes and methods do we want our vertex class to have? Hmm. Add connections (addNeighbor), know which nodes the current node connect with (getConnections), find out the name of the node (getId ), and how strong is the connection (getWeight)
Create a graph class with some basic methods of a graph:
Congratulation! In this article, you have learned what graph is and how to use a graph to visualize the social network. So what can you do with this knowledge? Maybe access to the data in this article and create the graph of the characters you are curious about to analyze their relationship?
Or if you are not at all a fan of Game of Thrones, you can analyze data about other social networks you care about such as Twitter, Facebook to analyze the network between you and your friends or followers. You will get to practice using the graph as well as understand your relationship with your friends. Do you know them directly or from the connections with others? It would be so fascinating to know!
You can find the code of this article in my Github. In my notebook, I also cover how to traverse the disconnected nodes with depth-first search, and find the distance between 2 characters with breadth-first search.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: