Some Networkx Examples
Table of Contents
The Departure
This is a look at different ways of creating and manipulating graphs using NetworkX.
Imports
Python
from functools import partial
from pathlib import Path
import os
PyPi
from bokeh.models import HoverTool
import holoviews
import hvplot.pandas
import networkx
import numpy
import pandas
My Stuff
from graeae.visualization import EmbedHoloview
Set Up
SLUG = "some-networkx-examples"
OUTPUT_PATH = Path("../../files/posts/networks/" + SLUG)
Embed = partial(EmbedHoloview, folder_path=OUTPUT_PATH)
The Initiation
Different Ways to Create Network Graphs
NetworkX has a few different ways to create graphs, some more flexible than others. This is a non-exhaustive showing of some of them.
Adding Edges To An Existing Graph
You can create a graph using the graph constructors. This is an example of an undirected Graph.
graph_1 = networkx.Graph()
G1.add_edges_from([(0, 1),
(0, 2),
(0, 3),
(0, 5),
(1, 3),
(1, 6),
(3, 4),
(4, 5),
(4, 7),
(5, 8),
(8, 9)])
networkx.draw_networkx(G1)
Adjacency List
with open("G_adjlist.txt") as reader:
print(reader.read())
G2 = networkx.read_adjlist('G_adjlist.txt', nodetype=int)
G2.edges()
Adjacency Matrix
G_mat = numpy.array([[0, 1, 1, 1, 0, 1, 0, 0, 0, 0],
[1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0]])
G_mat
G3 = networkx.Graph(G_mat)
G3.edges()
Edgelist
with open('G_edgelist.txt') as reader:
print(reader.read())
G4 = networkx.read_edgelist('G_edgelist.txt', data=[('Weight', int)])
G4.edges(data=True)
Pandas DataFrame
G_df = pandas.read_csv('G_edgelist.txt', delim_whitespace=True,
header=None, names=['n1', 'n2', 'weight'])
G_df
G5 = networkx.from_pandas_dataframe(G_df, 'n1', 'n2', edge_attr='weight')
G5.edges(data=True)
A Chess Example
with open('chess_graph.txt') as reader:
count = 0
for line in reader:
print(line.strip())
count += 1
if count == 5:
break
chess = networkx.read_edgelist('chess_graph.txt', data=[('outcome', int), ('timestamp', float)],
create_using=networkx.MultiDiGraph())
chess.is_directed(), chess.is_multigraph()
chess.edges(data=True)[:5]
games_played = chess.degree()
games_played
max_value = max(games_played.values())
max_key, = [i for i in games_played.keys() if games_played[i] == max_value]
print('player {}\n{} games'.format(max_key, max_value))
df = pd.DataFrame(chess.edges(data=True), columns=['white', 'black', 'outcome'])
df.head()
df['outcome'] = df['outcome'].map(lambda x: x['outcome'])
df.head()
won_as_white = df[df['outcome']==1].groupby('white').sum()
won_as_black = df[df['outcome']==-1].groupby('black').sum()
win_count = won_as_white.add(won_as_black, fill_value=0)
print(win_count.head())
win_count.nlargest(5, 'outcome')