import networkx as nx
import numpy as np
import matplotlib.pylab as plt
Let's create a new undirected Graph with three Nodes (A,B,C) that are all interconnected.
UG = nx.Graph()
UG.add_edge('A', 'B')
UG.add_edge('B', 'C')
UG.add_edge('C', 'A')
Let's have a look at what the returned "Graph" provides us with. dir
also works with modules
e.g. try replacing UG
with nx
.
", ".join(dir(UG)) # Instance of networkx.Graph
# ", ".join(dir(nx)) # The networkx module
# ", ".join(dir(nx.algorithms)) # The networkx.algorithms submodule
'__class__, __contains__, __delattr__, __dict__, __doc__, __format__, __getattribute__, __getitem__, __hash__, __init__, __iter__, __len__, __module__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, __weakref__, add_cycle, add_edge, add_edges_from, add_node, add_nodes_from, add_path, add_star, add_weighted_edges_from, adj, adjacency_iter, adjacency_list, clear, copy, degree, degree_iter, edge, edges, edges_iter, get_edge_data, graph, has_edge, has_node, is_directed, is_multigraph, name, nbunch_iter, neighbors, neighbors_iter, node, nodes, nodes_iter, nodes_with_selfloops, number_of_edges, number_of_nodes, number_of_selfloops, order, remove_edge, remove_edges_from, remove_node, remove_nodes_from, selfloop_edges, size, subgraph, to_directed, to_undirected'
for node in UG.nodes():
print node, UG.neighbors(node)
A ['C', 'B'] C ['A', 'B'] B ['A', 'C']
for node in UG.nodes():
print node, UG.degree(node)
A 2 C 2 B 2
print nx.degree(UG)
{'A': 2, 'C': 2, 'B': 2}
print UG.is_directed() and "Yes!" or "No."
No.
num_nodes = UG.number_of_nodes()
num_edges = UG.number_of_edges()
print "Nodes: %d" % num_nodes
print "Edges: %d" % num_edges
Nodes: 3 Edges: 3
nx.draw(UG, with_labels=True)
UG.add_node('D')
nx.draw(UG, with_labels=True)
UG.remove_node('C')
nx.draw(UG, with_labels=True)
RM = nx.random_graphs.erdos_renyi_graph(10, 0.15, seed=2015)
Let's print all nodes and their neighbours and check if the given graph is connected.
for node in RM.nodes():
print node, RM.neighbors(node)
0 [4, 6] 1 [5, 7] 2 [] 3 [6] 4 [0] 5 [1, 7] 6 [0, 8, 3, 7] 7 [1, 5, 6] 8 [6] 9 []
nx.is_connected(RM)
False
Since this graph is not connected - let's have a look at all subgraphs (components) if any.
for index, connected_component in enumerate(nx.connected_components(RM)):
print index, connected_component
0 [0, 1, 3, 4, 5, 6, 7, 8] 1 [2] 2 [9]
So, two dangling nodes and a large component with eight nodes.
nx.draw(RM, with_labels=True)
Let's have a look at the degree of each node.
degree_dict = nx.degree(RM)
degree_dict
{0: 2, 1: 2, 2: 0, 3: 1, 4: 1, 5: 2, 6: 4, 7: 3, 8: 1, 9: 0}
What's the highest degree in the network?
list(degree_dict.itervalues())
[2, 2, 0, 1, 1, 2, 4, 3, 1, 0]
max(degree_dict.itervalues())
4
Let's create a histogram showing how many nodes have degree k (for all k in G)
histogram, edges = np.histogram(list(degree_dict.itervalues()), bins=[1,2,3,4,5])
histogram, edges
(array([3, 3, 1, 1]), array([1, 2, 3, 4, 5]))
Given only the network of co-occurences. How can I (without reading the book or consulting any other sources) determine the most prominent character?
NOTE: Get the lesmis.gml from the 'websci1.zip' (on the course website). Adjust the path as necessary, use the "star_graph" or any other graph generator for that matter.
# G = nx.star_graph(20)
G = nx.read_gml("lesmis.gml")
# Find our most prominent actor.
degree_centrality = nx.degree_centrality(G)
central = max(degree_centrality.iterkeys(), key=lambda k: degree_centrality[k])
print "Most prominent actor is Node #%d and labeled '%s'" % (central, G.node[central]['label'])
# Jean Valjean, the character, not the asteroid ;)
Most prominent actor is Node #11 and labeled 'Valjean'
nx.draw(G, with_labels=True)
As we can clearly see node 11 is ... such network... much wow...
# Draw pretty graph based on degree centrality.
plt.figure(figsize=(8,8))
plt.axis('off')
pos = nx.spring_layout(G)
nx.draw_networkx_edges(G, pos, nodelist=[central], alpha=0.2)
nx.draw_networkx_nodes(G, pos, nodelist=degree_centrality.keys(),
node_size=30,
node_color=degree_centrality.values(),
cmap=plt.cm.Greys_r) # 8-bits of gray
# Highlight our most prominent actor.
nx.draw_networkx_nodes(G, pos, nodelist=[central],
node_size=90,
node_color='yellow')
# Store the plot on disk.
plt.savefig("lesmis_degree_centrality.png")
plt.show()