Network Diagrams
DS 2023 | Communicating with Data

Overview¶
Networks diagrams are visual representations of mathematical graph.
A graph consists of a set of vertices, or nodes, and edges, or links.
Typically, nodes are represented as shapes, like circles, and edges are represented as lines.
Nodes may represent individuals, groups, or categories, and edges represent any kind of relationship between those nodes.
For example, nodes can stand for individual people and edges can stand for relationships between people.
Nodes can also stand for abstract entities like ideas and edges can stand for the logical relationships between them.
There are numerous methods for arranging nodes and edges in a diagram, from force directed to circular to hierarchical layouts.
Use cases¶
Network diagrams can be used to detect centrality, betweenness, and other properties of graphs.
They are particularly useful for social network analysis (SNA).
Networks diagrams can be used to detect outliers and clusters.
They are also great at showing structural patterns in populations.
A simple example¶
We will begin with the Penguins dataset.
We are going to create a “bipartite” graph.
This means we are going to see how two categorical variables are related to each other.
For this example, we will look at species and island, two variables we have looked at through other lenses.
Import the libraries.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snsRead in the data.
penguins = sns.load_dataset('penguins').dropna()
graph_cols = ['species','island']
penguins[graph_cols] = penguins[graph_cols].astype('category')
penguins.head()Create a table of nodes.
We first need to create a table of nodes.
Nodes are the unique values of the variables we have chosen, along with some properties.
An easy way to generate this table is with value_counts.
nodes = penguins[graph_cols].melt().value_counts().to_frame().reset_index()
nodes['weight'] = nodes['count'] / nodes['count'].sum()
nodes.index.name = 'node_id'
nodesCreate node types table.
We also want to have data associated with the types of node.
This will make it easy to define display attributes, such as shape and color, as visualization time.
node_types = nodes['variable'].value_counts().to_frame()
node_types['color'] = ['#dce9f2', '#d9f0a3']
node_types['shape'] = ['circle', 'rectangle']
node_typesAdd node type attributes to nodes.
We join the type data with the node instances for convenient access.
nodes['color'] = nodes['variable'].map(node_types['color'])
nodes['shape'] = nodes['variable'].map(node_types['shape'])
nodesCreate a table of edges, aka links.
Next, we create the links.
These are all the relationships between our two variables.
As with alluvials, we want all the combinations of the domains in the two variables.
An easy way to generate these is, again, with value_counts.
edges = penguins.value_counts(graph_cols).reset_index()
edges['weight'] = edges['count'] / edges['count'].sum()
edges.index.name = 'edge_id'
edges.head()We also want to provide the IDs of the nodes.
Note that we remove combinations without counts.
edges['source'] = edges['species'].map(nodes.reset_index().set_index('value').node_id)
edges['target'] = edges['island'].map(nodes.reset_index().set_index('value').node_id)
edges.index.name = 'edge_id'
edges = edges[edges['count'] > 0]
edgesNow let’s create a crude visualization of the graph.
fig, ax = plt.subplots(figsize=(6,6))
# Plot the nodes
for idx, row in nodes.iterrows():
var, val = row[['variable','value']]
x = node_types.index.get_loc(var)
y = penguins[var].cat.categories.to_list().index(val)
nodes.loc[idx, 'x'] = x
nodes.loc[idx, 'y'] = y
color = node_types.loc[var, 'color']
markersize = row['weight'] * 200
ax.plot(x, y, 'o', markersize=markersize, c=color)
ax.text(x+.08, y+.05, val)
# Plot the edges
for idx, row in edges.iterrows():
src, tgt = row[['source','target']]
x1, y1 = nodes.loc[src, ['x','y']]
x2, y2 = nodes.loc[tgt, ['x','y']]
lw = row['weight'] * 10
ax.plot([x1, x2], [y1, y2], '--', lw=lw, c='gray')
# Spruce things up
sns.despine(left=True, bottom=True)
plt.xlim(-.1, 1.1)
plt.ylim(-.2, 2.2)
plt.xticks([])
plt.yticks([])
plt.title("Simple Graph of Species and Islands", y=1.01)
plt.show()
Pause to inspect the properties of the graph.
In particular, check out the degrees:
For Adelie, , meaning it lives on three islands.
For Torgersen and Gentoo, , meaning they each have only one relationship.
Using iGraph¶
Create the graph object.
IGraph will take our node and edge tables and create a graph object from them.
A graph object will contain all the data, plus a bunch of graph theoretical computions.
It is also capable of being plotted.
To create the graph, we just move our data into the object.
import igraph as ig
pg = ig.Graph(edges=edges[['source','target']].values.tolist())
# Add node properties
pg.vs['label'] = nodes['value'].to_list()
pg.vs['count'] = nodes['count'].to_list()
pg.vs['weight'] = nodes['weight'].to_list()
pg.vs['node_type'] = nodes['variable'].to_list()
pg.vs['shape'] = nodes["shape"].tolist()
pg.vs['color'] = nodes["color"].tolist()
# Add edge properties
pg.es['weight'] = edges['weight'].tolist() Plot the graph.
Plotting is a matter of calling the plot function and passing it the graph object along with parameters.
Note that some parameters — e.g. shape and color — don’t need to be given in the plotting function since they are already defined in the object.
fig, ax = plt.subplots(figsize=(8, 6))
ig.plot(
pg,
target=ax,
layout="auto",
vertex_size=100,
vertex_frame_width=0,
vertex_label_size=11,
edge_color="gray",
edge_width=3,
)
ax.set_aspect("equal")
plt.show()
Size nodes and edges with weights.
We can also resize the nodes and edges based on their weights.
fig, ax = plt.subplots(figsize=(8, 6))
ig.plot(
pg,
target=ax,
layout="auto",
vertex_size=nodes['weight'] * 500,
vertex_frame_width=0,
vertex_label_size=11,
edge_color="gray",
edge_width=edges['weight'] * 25,
)
plt.show()
Finally, we can specify a different layout algorithm.
Here are all the options:

See the documentation for layout options.
Here we specify tree.
fig, ax = plt.subplots(figsize=(8, 6))
ig.plot(
pg,
target=ax,
layout="tree",
vertex_size=nodes['weight'] * 500,
vertex_frame_width=0,
vertex_label_size=11,
edge_color="gray",
edge_width=edges['weight'] * 25,
)
plt.show()
A bigger example¶
Let’s look at a larger dataset.
We will explore a dataset of wine reviews.
We will create a network out of wine reviewers (tasters) and the countries whose wine they tend to review.
data_url = "https://virginia.box.com/shared/static/5v7689y0pc7vlhwsgrc1vtozivfzyvps.csv"
DOC = pd.read_csv(data_url)
DOC = DOC.dropna(subset=['doc_taster', 'doc_country', 'doc_variety']) # Drop rows with nulls values in key cols
DOC.head()Get shape of data set.
DOC.shape(71605, 19)Create the nodes and edges.
node_cols = ['doc_country', 'doc_taster']NODES = DOC[node_cols].melt().value_counts().to_frame()
NODES = NODES.reset_index()
NODES.index.name = 'node_id'
NODES['weight'] = NODES['count'] / NODES['count'].sum()
NODES.head()Add node styles.
NODE_TYPES = NODES['variable'].value_counts().to_frame()
NODE_TYPES['color'] = ['#dce9f2', '#d9f0a3']
NODE_TYPES['shape'] = ['circle', 'rectangle']
NODES['color'] = NODES['variable'].map(NODE_TYPES['color'])
NODES['shape'] = NODES['variable'].map(NODE_TYPES['shape'])
NODES.head()EDGES = DOC[node_cols].value_counts().to_frame().reset_index()
EDGES.index.name = 'edge_id'
EDGES['weight'] = EDGES['count'] / EDGES['count'].sum()
EDGES.head()EDGES['source'] = EDGES['doc_country'].map(NODES.reset_index().set_index('value').node_id)
EDGES['target'] = EDGES['doc_taster'].map(NODES.reset_index().set_index('value').node_id)
EDGES = EDGES.query("count > 0") # Remove edges with no examples
EDGES.sample(10)Convert to graph
g = ig.Graph(edges=EDGES[['source', 'target']].values.tolist())
g.vs['value'] = NODES['value'].to_list()
g.vs['count'] = NODES['count'].to_list()
g.vs['weight'] = NODES['weight'].to_list()
g.vs['node_type'] = NODES['variable'].to_list()
g.vs['shape'] = NODES["shape"].tolist()
g.vs['color'] = NODES["color"].tolist()
g.es['weight'] = EDGES['count'].tolist()
g.es['weight'] = EDGES['weight'].tolist()Explore graph properties.
NODES['indegree'] = g.vs.indegree()
(
NODES
.query("variable == 'doc_taster'")
.sort_values('indegree')
.plot.barh(x='value', y='indegree',
legend=False, title="In-degree of Taster Nodes")
)
plt.show()
NODES['betweenness'] = g.vs.betweenness()
(
NODES
.query("variable == 'doc_taster'")
.sort_values('betweenness')
.plot.barh(x='value', y='betweenness',
legend=False, title="Betweenness of Taster Nodes")
)
plt.show()
NODES['betweenness'] = g.vs.betweenness()
(
NODES
.query("variable == 'doc_country'")
.sort_values('betweenness')
.plot.barh(x='value', y='betweenness',
legend=False, title="Betweenness of Country Nodes")
)
plt.show()
NODES['pagerank'] = g.vs.pagerank()
(
NODES
.query("variable == 'doc_taster'")
.sort_values('pagerank')
.plot.barh(x='value', y='pagerank',
legend=False, title="Page Rank of Taster Nodes")
)
plt.show()
Plot.
layout_type = "rt_circular"
# layout_type = "rt"fig, ax = plt.subplots(figsize=(20,20))
ig.plot(
g,
target = ax,
layout = layout_type,
vertex_size = 70,
vertex_frame_width = 1.0,
vertex_frame_color = "gray",
vertex_label = g.vs["value"],
vertex_label_size = 12.0,
edge_color = 'gray'
)
plt.title(f"Tasters and Countries\n({layout_type})", fontsize=20)
plt.show()
fig, ax = plt.subplots(figsize=(20,20))
ig.plot(
g,
target = ax,
layout = layout_type,
vertex_size = pd.Series(g.vs['weight']) * 500,
vertex_frame_width = 1,
vertex_frame_color = "gray",
vertex_label = g.vs["value"],
vertex_label_size = 14,
edge_color = 'gray',
edge_width = pd.Series(g.es['weight']) * 100
)
plt.title(f"Tasters and Countries\n({layout_type})", fontsize=20)
plt.show()
Generalize¶
We create three functions to generalize the pattern demonstrated above.
Note that we can easily convert these functions into a single object that would have a method to directly plot a network from a dataframe and node columns.
def tidy_to_graph(df:pd.DataFrame, node_cols:list):
"""
Converts columns from a tidy table into a graph comprised of NODES and EDGES data frames.
Works for bipartite graphs -- graphs with connections between two columns.
"""
# Create nodes
NODES = df[node_cols].melt().value_counts().to_frame()
NODES = NODES.reset_index()
NODES['weight'] = NODES['count'] / NODES['count'].sum()
NODES.index.name = 'node_id'
# Add styles
NODE_TYPES = NODES['variable'].value_counts().to_frame()
NODE_TYPES['color'] = ['#dce9f2', '#d9f0a3']
NODE_TYPES['shape'] = ['circle', 'rectangle']
NODES['color'] = NODES['variable'].map(NODE_TYPES['color'])
NODES['shape'] = NODES['variable'].map(NODE_TYPES['shape'])
# Create edges
EDGES = df[node_cols].value_counts().to_frame().reset_index()
EDGES['weight'] = EDGES['count'] / EDGES['count'].sum()
EDGES.index.name = 'edge_id'
# Replace
EDGES['source'] = EDGES[node_cols[0]].map(NODES.reset_index().set_index('value').node_id)
EDGES['target'] = EDGES[node_cols[1]].map(NODES.reset_index().set_index('value').node_id)
EDGES = EDGES.query("count > 0") # Remove edges with no examples
# Returns both data frames
return NODES, EDGES
def graph_to_igraph(NODES:pd.DataFrame, EDGES:pd.DataFrame, directed:bool=False):
"""
Converts NODES and EDGES directly into an igraph Graph object.
"""
# Create graph from EDGES
g = ig.Graph(edges=EDGES[['source', 'target']].values.tolist())
# Add vertex (node) attributes
g.vs['label'] = NODES['value'].to_list()
g.vs['count'] = NODES['count'].to_list()
g.vs['weight'] = NODES['weight'].to_list()
g.vs['node_type'] = NODES['variable'].to_list()
g.vs['shape'] = NODES["shape"].tolist()
g.vs['color'] = NODES["color"].tolist()
g.es['weight'] = EDGES['weight'].tolist()
# Add edge attributes
g.es['weight'] = EDGES['weight'].tolist()
return gdef graphplot(my_g, layout_type='rt_circular', node_size:int=None, edge_size:int=None, title=None, figsize=(20,20)):
v_s = pd.Series(my_g.vs['weight']) * node_size if node_size else None
e_w = pd.Series(my_g.es['weight']) * edge_size if edge_size else None
fig, ax = plt.subplots(figsize=figsize)
ig.plot(
my_g,
target = ax,
layout = layout_type,
edge_width = e_w,
vertex_size = v_s,
vertex_frame_width = 1,
vertex_frame_color = "gray",
vertex_label = my_g.vs["label"],
vertex_label_size = 12,
edge_color = 'gray'
)
plt.title(title, fontsize=20)
plt.show()Test out the functions.
my_node_cols = ['doc_taster', 'doc_country']
N, E = tidy_to_graph(DOC, my_node_cols)
G = graph_to_igraph(N, E)
graphplot(G, edge_size=100, node_size=500)
my_node_cols = ['doc_country', 'doc_variety']
N, E = tidy_to_graph(DOC, my_node_cols)
G = graph_to_igraph(N, E)
graphplot(G, 'tree')